Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/VeryLiquidVault.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ERC4626Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Auth, DEFAULT_ADMIN_ROLE, GUARDIAN_ROLE, STRATEGIST_ROLE, VAULT_MANAGER_ROLE} from "@src/Auth.sol";
import {IVault} from "@src/IVault.sol";
import {BaseVault} from "@src/utils/BaseVault.sol";
import {PerformanceVault} from "@src/utils/PerformanceVault.sol";
/// @title VeryLiquidVault
/// @custom:security-contact security@size.credit
/// @author Size (https://size.credit/)
/// @notice Very Liquid Vault that distributes assets across multiple strategies
/// @dev Extends PerformanceVault to manage multiple strategy vaults for asset allocation. By default, the performance fee is 0.
contract VeryLiquidVault is PerformanceVault {
using SafeERC20 for IERC20;
/// @dev The maximum number of strategies that can be added to the vault
uint256 private constant MAX_STRATEGIES = 10;
/// @dev The default maximum slippage percent for rebalancing in PERCENT
uint256 private constant DEFAULT_MAX_SLIPPAGE_PERCENT = 0.01e18;
// STORAGE
/// @custom:storage-location erc7201:vlv.storage.VeryLiquidVault
struct VeryLiquidVaultStorage {
IVault[] _strategies;
uint256 _rebalanceMaxSlippagePercent;
}
// keccak256(abi.encode(uint256(keccak256("vlv.storage.VeryLiquidVault")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant VeryLiquidVaultStorageLocation =
0x851713d8b7886cdb5682ccb4d2dba1bf8cae30c699ce588016da31dab5d7f100;
function _getVeryLiquidVaultStorage() private pure returns (VeryLiquidVaultStorage storage $) {
assembly {
$.slot := VeryLiquidVaultStorageLocation
}
}
// EVENTS
event StrategyAdded(address indexed strategy);
event StrategyRemoved(address indexed strategy);
event StrategyReordered(address indexed strategyOld, address indexed strategyNew, uint256 indexed index);
event Rebalanced(
address indexed strategyFrom, address indexed strategyTo, uint256 rebalancedAmount, uint256 maxSlippagePercent
);
event RebalanceMaxSlippagePercentSet(
uint256 oldRebalanceMaxSlippagePercent, uint256 newRebalanceMaxSlippagePercent
);
event DepositFailed(address indexed strategy, uint256 amount);
event WithdrawFailed(address indexed strategy, uint256 amount);
// ERRORS
error InvalidStrategy(address strategy);
error CannotDepositToStrategies(uint256 assets, uint256 shares, uint256 remainingAssets);
error CannotWithdrawFromStrategies(uint256 assets, uint256 shares, uint256 missingAssets);
error TransferredAmountLessThanMin(
uint256 assetsBefore, uint256 assetsAfter, uint256 slippage, uint256 amount, uint256 maxSlippagePercent
);
error MaxStrategiesExceeded(uint256 strategiesCount, uint256 maxStrategies);
error ArrayLengthMismatch(uint256 expectedLength, uint256 actualLength);
error InvalidMaxSlippagePercent(uint256 maxSlippagePercent);
// CONSTRUCTOR / INITIALIZER
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initializes the VeryLiquidVault with strategies
/// @param auth_ The address of the Auth contract
/// @param asset_ The address of the asset
/// @param name_ The name of the vault
/// @param symbol_ The symbol of the vault
/// @param fundingAccount The address of the funding account for the first deposit, which will be treated as dead shares
/// @param firstDepositAmount The amount of the first deposit, which will be treated as dead shares
/// @param strategies_ The initial strategies to add to the vault
function initialize(
Auth auth_,
IERC20 asset_,
string memory name_,
string memory symbol_,
address fundingAccount,
uint256 firstDepositAmount,
IVault[] memory strategies_
) public virtual initializer {
__PerformanceVault_init(auth_.getRoleMember(DEFAULT_ADMIN_ROLE, 0), 0);
for (uint256 i = 0; i < strategies_.length; ++i) {
_addStrategy(strategies_[i], address(asset_), address(auth_));
}
_setRebalanceMaxSlippagePercent(DEFAULT_MAX_SLIPPAGE_PERCENT);
super.initialize(auth_, asset_, name_, symbol_, fundingAccount, firstDepositAmount);
}
// ERC4626 OVERRIDES
/// @inheritdoc ERC4626Upgradeable
/// @dev The maximum amount that can be deposited is the minimum between this receiver specific limit and the maximum asset amount that can be deposited to all strategies
function maxDeposit(address receiver) public view override(BaseVault) returns (uint256) {
return Math.min(_maxDepositToStrategies(), super.maxDeposit(receiver));
}
/// @inheritdoc ERC4626Upgradeable
/// @dev The maximum amount that can be minted is the minimum between this receiver specific limit and the maximum asset amount that can be minted to all strategies, converted to shares
function maxMint(address receiver) public view override(BaseVault) returns (uint256) {
uint256 maxDepositReceiver = maxDeposit(receiver);
// slither-disable-next-line incorrect-equality
uint256 maxDepositInShares = maxDepositReceiver == type(uint256).max
? type(uint256).max
: _convertToShares(maxDepositReceiver, Math.Rounding.Floor);
return Math.min(maxDepositInShares, super.maxMint(receiver));
}
/// @inheritdoc ERC4626Upgradeable
/// @dev The maximum amount that can be withdrawn is the minimum between this owner specific limit and the maximum asset amount that can be withdrawn from all strategies
function maxWithdraw(address owner) public view override(BaseVault) returns (uint256) {
return Math.min(_maxWithdrawFromStrategies(), super.maxWithdraw(owner));
}
/// @inheritdoc ERC4626Upgradeable
/// @dev The maximum amount that can be redeemed is the minimum between this owner specific limit and the maximum asset amount that can be redeemed from all strategies, converted to shares
function maxRedeem(address owner) public view override(BaseVault) returns (uint256) {
uint256 maxWithdrawOwner = maxWithdraw(owner);
// slither-disable-next-line incorrect-equality
uint256 maxWithdrawInShares = maxWithdrawOwner == type(uint256).max
? type(uint256).max
: _convertToShares(maxWithdrawOwner, Math.Rounding.Floor);
return Math.min(maxWithdrawInShares, super.maxRedeem(owner));
}
/// @inheritdoc ERC4626Upgradeable
/// @dev The total assets is the sum of the assets in all strategies
// slither-disable-next-line calls-loop
function totalAssets() public view virtual override(ERC4626Upgradeable, IERC4626) returns (uint256 total) {
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
for (uint256 i = 0; i < length; ++i) {
IVault strategy = $._strategies[i];
uint256 strategyBalance = strategy.balanceOf(address(this));
// slither-disable-next-line incorrect-equality
if (strategyBalance == 0) continue;
total += strategy.convertToAssets(strategyBalance);
}
}
/// @inheritdoc ERC4626Upgradeable
/// @dev Tries to deposit to strategies sequentially, reverts if not all assets can be deposited
// slither-disable-next-line calls-loop
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal override {
if (_isInitializing()) {
// first deposit
shares = assets;
}
super._deposit(caller, receiver, assets, shares);
uint256 assetsToDeposit = assets;
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
for (uint256 i = 0; i < length; ++i) {
// slither-disable-next-line incorrect-equality
if (assetsToDeposit == 0) break;
IVault strategy = $._strategies[i];
uint256 strategyMaxDeposit = strategy.maxDeposit(address(this));
uint256 depositAmount = Math.min(assetsToDeposit, strategyMaxDeposit);
if (depositAmount > 0) {
IERC20(asset()).forceApprove(address(strategy), depositAmount);
// slither-disable-next-line unused-return
try strategy.deposit(depositAmount, address(this)) {
assetsToDeposit -= depositAmount;
} catch {
emit DepositFailed(address(strategy), depositAmount);
IERC20(asset()).forceApprove(address(strategy), 0);
}
}
}
if (assetsToDeposit > 0) revert CannotDepositToStrategies(assets, shares, assetsToDeposit);
}
/// @inheritdoc ERC4626Upgradeable
/// @dev Tries to withdraw from strategies sequentially, reverts if not enough assets available
// slither-disable-next-line calls-loop
function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)
internal
override
{
uint256 assetsToWithdraw = assets;
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
for (uint256 i = 0; i < length; ++i) {
// slither-disable-next-line incorrect-equality
if (assetsToWithdraw == 0) break;
IVault strategy = $._strategies[i];
uint256 strategyMaxWithdraw = strategy.maxWithdraw(address(this));
uint256 withdrawAmount = Math.min(assetsToWithdraw, strategyMaxWithdraw);
if (withdrawAmount > 0) {
// slither-disable-next-line unused-return
try strategy.withdraw(withdrawAmount, address(this), address(this)) {
assetsToWithdraw -= withdrawAmount;
} catch {
emit WithdrawFailed(address(strategy), withdrawAmount);
}
}
}
if (assetsToWithdraw > 0) revert CannotWithdrawFromStrategies(assets, shares, assetsToWithdraw);
super._withdraw(caller, receiver, owner, assets, shares);
}
// ADMIN FUNCTIONS
/// @notice Sets the performance fee percent
/// @param performanceFeePercent_ The new performance fee percent
/// @dev Only callable by addresses with DEFAULT_ADMIN_ROLE
function setPerformanceFeePercent(uint256 performanceFeePercent_)
external
nonReentrant
onlyAuth(DEFAULT_ADMIN_ROLE)
{
_setPerformanceFeePercent(performanceFeePercent_);
}
/// @notice Sets the fee recipient
/// @param feeRecipient_ The new fee recipient
/// @dev Only callable by addresses with DEFAULT_ADMIN_ROLE
function setFeeRecipient(address feeRecipient_) external nonReentrant onlyAuth(DEFAULT_ADMIN_ROLE) {
_setFeeRecipient(feeRecipient_);
}
// VAULT MANAGER FUNCTIONS
/// @notice Sets the rebalance max slippage percent
/// @param rebalanceMaxSlippagePercent_ The new rebalance max slippage percent
/// @dev Only callable by addresses with VAULT_MANAGER_ROLE
function setRebalanceMaxSlippagePercent(uint256 rebalanceMaxSlippagePercent_)
external
nonReentrant
onlyAuth(VAULT_MANAGER_ROLE)
{
_setRebalanceMaxSlippagePercent(rebalanceMaxSlippagePercent_);
}
/// @notice Adds a new strategy to the vault
/// @param strategy_ The new strategy to add
/// @dev Only callable by addresses with VAULT_MANAGER_ROLE
function addStrategy(IVault strategy_) external nonReentrant emitVaultStatus onlyAuth(VAULT_MANAGER_ROLE) {
_addStrategy(strategy_, asset(), address(auth()));
}
// GUARDIAN FUNCTIONS
/// @notice Removes a strategy from the vault and transfers all assets, if any, to another strategy
/// @param strategyToRemove The strategy to remove
/// @param strategyToReceiveAssets The strategy to receive the assets
/// @param amount The amount of assets to transfer
/// @param maxSlippagePercent The maximum slippage percent allowed for the rebalance
/// @dev Only callable by addresses with GUARDIAN_ROLE
/// @dev Using `amount` = 0 will forfeit all assets from `strategyToRemove`
/// @dev Using `amount` = type(uint256).max will attempt to transfer the entire balance from `strategyToRemove`
/// @dev If `convertToAssets(balanceOf)` > `maxWithdraw`, e.g. due to pause/withdraw limits, the _rebalance step will revert, so an appropriate `amount` should be used
/// @dev Reverts if totalAssets() == 0 at the end of the operation, which can happen if the call is performed with 100% slippage
// slither-disable-next-line reentrancy-no-eth
function removeStrategy(
IVault strategyToRemove,
IVault strategyToReceiveAssets,
uint256 amount,
uint256 maxSlippagePercent
) external nonReentrant emitVaultStatus onlyAuth(GUARDIAN_ROLE) {
if (!_isStrategy(strategyToRemove)) revert InvalidStrategy(address(strategyToRemove));
if (!_isStrategy(strategyToReceiveAssets)) revert InvalidStrategy(address(strategyToReceiveAssets));
if (strategyToRemove == strategyToReceiveAssets) revert InvalidStrategy(address(strategyToReceiveAssets));
if (amount > 0) {
uint256 assetsToRemove = strategyToRemove.convertToAssets(strategyToRemove.balanceOf(address(this)));
amount = Math.min(amount, assetsToRemove);
_rebalance(strategyToRemove, strategyToReceiveAssets, amount, maxSlippagePercent);
}
_removeStrategy(strategyToRemove);
// slither-disable-next-line incorrect-equality
if (totalAssets() == 0) revert NullAmount();
}
// STRATEGIST FUNCTIONS
/// @notice Reorders the strategies
/// @param newStrategiesOrder The new strategies order
/// @dev Only callable by addresses with STRATEGIST_ROLE
/// @dev Verifies that the new strategies order is valid and that there are no duplicates
/// @dev Clears current strategies and adds them in the new order
function reorderStrategies(IVault[] calldata newStrategiesOrder) external nonReentrant onlyAuth(STRATEGIST_ROLE) {
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
if (length != newStrategiesOrder.length) revert ArrayLengthMismatch(length, newStrategiesOrder.length);
for (uint256 i = 0; i < length; ++i) {
if (!_isStrategy(newStrategiesOrder[i])) revert InvalidStrategy(address(newStrategiesOrder[i]));
for (uint256 j = i + 1; j < length; ++j) {
if (newStrategiesOrder[i] == newStrategiesOrder[j]) {
revert InvalidStrategy(address(newStrategiesOrder[i]));
}
}
}
for (uint256 i = 0; i < length; ++i) {
IVault strategyOld = $._strategies[i];
$._strategies[i] = newStrategiesOrder[i];
emit StrategyReordered(address(strategyOld), address(newStrategiesOrder[i]), i);
}
}
/// @notice Rebalances assets between two strategies
/// @param strategyFrom The strategy to transfer assets from
/// @param strategyTo The strategy to transfer assets to
/// @param amount The amount of assets to transfer
/// @param maxSlippagePercent The maximum slippage percent allowed for the rebalance
/// @dev Only callable by addresses with STRATEGIST_ROLE
/// @dev Transfers assets from one strategy to another
/// @dev We have maxSlippagePercent <= PERCENT since rebalanceMaxSlippagePercent has already been checked in setRebalanceMaxSlippagePercent
function rebalance(IVault strategyFrom, IVault strategyTo, uint256 amount, uint256 maxSlippagePercent)
external
nonReentrant
notPaused
emitVaultStatus
onlyAuth(STRATEGIST_ROLE)
{
maxSlippagePercent = Math.min(maxSlippagePercent, _rebalanceMaxSlippagePercent());
amount = Math.min(amount, strategyFrom.maxWithdraw(address(this)));
if (!_isStrategy(strategyFrom)) revert InvalidStrategy(address(strategyFrom));
if (!_isStrategy(strategyTo)) revert InvalidStrategy(address(strategyTo));
if (strategyFrom == strategyTo) revert InvalidStrategy(address(strategyTo));
if (amount == 0) revert NullAmount();
_rebalance(strategyFrom, strategyTo, amount, maxSlippagePercent);
}
// PRIVATE FUNCTIONS
/// @notice Internal function to add a strategy
/// @param strategy_ The strategy to add
/// @param asset_ The asset of the strategy
/// @param auth_ The auth of the strategy
/// @dev Strategy configuration is assumed to be correct (non-malicious, no circular dependencies, etc.)
// slither-disable-next-line calls-loop
function _addStrategy(IVault strategy_, address asset_, address auth_) private {
if (address(strategy_) == address(0)) revert NullAddress();
if (_isStrategy(strategy_)) revert InvalidStrategy(address(strategy_));
if (strategy_.asset() != asset_ || address(strategy_.auth()) != auth_) {
revert InvalidStrategy(address(strategy_));
}
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
$._strategies.push(strategy_);
emit StrategyAdded(address(strategy_));
if ($._strategies.length > MAX_STRATEGIES) revert MaxStrategiesExceeded($._strategies.length, MAX_STRATEGIES);
}
/// @notice Internal function to remove a strategy
/// @param strategy The strategy to remove
/// @dev No NullAddress check is needed because only whitelisted strategies can be removed, and it is checked in _addStrategy
/// @dev Removes the strategy in-place to keep the order
function _removeStrategy(IVault strategy) private {
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
for (uint256 i = 0; i < $._strategies.length; ++i) {
if ($._strategies[i] == strategy) {
for (uint256 j = i; j < $._strategies.length - 1; ++j) {
$._strategies[j] = $._strategies[j + 1];
}
$._strategies.pop();
emit StrategyRemoved(address(strategy));
break;
}
}
}
/// @notice Internal function to set the default max slippage percent
/// @param rebalanceMaxSlippagePercent_ The new rebalance max slippage percent
function _setRebalanceMaxSlippagePercent(uint256 rebalanceMaxSlippagePercent_) private {
if (rebalanceMaxSlippagePercent_ > PERCENT) revert InvalidMaxSlippagePercent(rebalanceMaxSlippagePercent_);
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 oldRebalanceMaxSlippagePercent = $._rebalanceMaxSlippagePercent;
$._rebalanceMaxSlippagePercent = rebalanceMaxSlippagePercent_;
emit RebalanceMaxSlippagePercentSet(oldRebalanceMaxSlippagePercent, rebalanceMaxSlippagePercent_);
}
/// @notice Internal function to calculate maximum depositable amount in all strategies
/// @dev The maximum amount that can be deposited to all strategies is the sum of the maximum amount that can be deposited to each strategy
/// @dev This value might be overstated if nested strategies are used. For example, if a very liquid has two strategies, one of which is an ERC4626StrategyVault and the other is a VeryLiquidVault that has the same ERC4626StrategyVault instance. In this scenario, if the ERC-4626 strategy has 100 maxDeposit remaining, the top-level very liquid would double count this value and return 200. However, in practice, trying to deposit 200 would cause a revert, because only 100 can be deposited.
// slither-disable-next-line calls-loop
function _maxDepositToStrategies() private view returns (uint256 maxAssets) {
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
for (uint256 i = 0; i < length; ++i) {
maxAssets = Math.saturatingAdd(maxAssets, $._strategies[i].maxDeposit(address(this)));
if (maxAssets == type(uint256).max) break;
}
}
/// @notice Internal function to calculate maximum withdrawable amount from all strategies
/// @dev The maximum amount that can be withdrawn from all strategies is the sum of the maximum amount that can be withdrawn from each strategy
/// @dev This value might be overstated if nested strategies are used. For example, if a very liquid has two strategies, one of which is an ERC4626StrategyVault and the other is a VeryLiquidVault that has the same ERC4626StrategyVault instance. In this scenario, if the ERC-4626 strategy has 100 maxWithdraw remaining, the top-level very liquid would double count this value and return 200. However, in practice, trying to withdraw 200 would cause a revert, because only 100 can be withdrawn.
// slither-disable-next-line calls-loop
function _maxWithdrawFromStrategies() private view returns (uint256 maxAssets) {
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
for (uint256 i = 0; i < length; ++i) {
maxAssets = Math.saturatingAdd(maxAssets, $._strategies[i].maxWithdraw(address(this)));
if (maxAssets == type(uint256).max) break;
}
}
/// @notice Internal function to rebalance assets between two strategies
/// @dev If before - after > maxSlippagePercent * amount, the _rebalance operation reverts
/// @dev Assumes input is validated by caller functions
/// @param strategyFrom The strategy to transfer assets from
/// @param strategyTo The strategy to transfer assets to
/// @param amount The amount of assets to transfer
/// @param maxSlippagePercent The maximum slippage percent allowed for the rebalance
function _rebalance(IVault strategyFrom, IVault strategyTo, uint256 amount, uint256 maxSlippagePercent) private {
uint256 assetsBefore = strategyFrom.convertToAssets(strategyFrom.balanceOf(address(this)))
+ strategyTo.convertToAssets(strategyTo.balanceOf(address(this)));
uint256 balanceBefore = IERC20(asset()).balanceOf(address(this));
if (amount > 0) {
// slither-disable-next-line unused-return
strategyFrom.withdraw(amount, address(this), address(this));
}
uint256 balanceAfter = IERC20(asset()).balanceOf(address(this));
uint256 assets = balanceAfter - balanceBefore;
if (assets > 0) {
IERC20(asset()).forceApprove(address(strategyTo), assets);
// slither-disable-next-line unused-return
strategyTo.deposit(assets, address(this));
}
uint256 assetsAfter = strategyFrom.convertToAssets(strategyFrom.balanceOf(address(this)))
+ strategyTo.convertToAssets(strategyTo.balanceOf(address(this)));
uint256 slippage = Math.mulDiv(maxSlippagePercent, amount, PERCENT);
if (assetsBefore > slippage + assetsAfter) {
revert TransferredAmountLessThanMin(assetsBefore, assetsAfter, slippage, amount, maxSlippagePercent);
}
emit Rebalanced(address(strategyFrom), address(strategyTo), assets, maxSlippagePercent);
}
// VIEW FUNCTIONS
/// @notice Returns the strategies in the vault
/// @return The strategies in the vault
function strategies() public view nonReentrantView returns (IVault[] memory) {
return _strategies();
}
/// @notice Internal function to get the strategies in the vault
function _strategies() private view returns (IVault[] memory) {
return _getVeryLiquidVaultStorage()._strategies;
}
/// @notice Returns the strategy at the given index
/// @param index The index of the strategy
/// @return The strategy at the given index
function strategies(uint256 index) public view nonReentrantView returns (IVault) {
return _getVeryLiquidVaultStorage()._strategies[index];
}
/// @notice Returns the number of strategies in the vault
/// @return The number of strategies in the vault
function strategiesCount() public view nonReentrantView returns (uint256) {
return strategies().length;
}
/// @notice Returns the rebalance max slippage percent
/// @return The rebalance max slippage percent
function rebalanceMaxSlippagePercent() public view nonReentrantView returns (uint256) {
return _rebalanceMaxSlippagePercent();
}
/// @notice Internal function to get the rebalance max slippage percent
function _rebalanceMaxSlippagePercent() private view returns (uint256) {
return _getVeryLiquidVaultStorage()._rebalanceMaxSlippagePercent;
}
/// @notice Returns true if the strategy is in the vault
/// @param strategy The strategy to check
/// @return True if the strategy is in the vault
function isStrategy(IVault strategy) public view nonReentrantView returns (bool) {
return _isStrategy(strategy);
}
/// @notice Internal function to check if the strategy is in the vault
function _isStrategy(IVault strategy) private view returns (bool) {
VeryLiquidVaultStorage storage $ = _getVeryLiquidVaultStorage();
uint256 length = $._strategies.length;
for (uint256 i = 0; i < length; ++i) {
if ($._strategies[i] == strategy) return true;
}
return false;
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
* The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
* and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
* itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
* offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
* of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
* With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
* underlying math can be found xref:ROOT:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {
using Math for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
struct ERC4626Storage {
IERC20 _asset;
uint8 _underlyingDecimals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;
function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {
assembly {
$.slot := ERC4626StorageLocation
}
}
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
*/
function __ERC4626_init(IERC20 asset_) internal onlyInitializing {
__ERC4626_init_unchained(asset_);
}
function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {
ERC4626Storage storage $ = _getERC4626Storage();
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
$._underlyingDecimals = success ? assetDecimals : 18;
$._asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
ERC4626Storage storage $ = _getERC4626Storage();
return address($._asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
return IERC20(asset()).balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}. */
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
// If asset() is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom(IERC20(asset()), caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If asset() is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer(IERC20(asset()), receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}
"
},
"lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}\
Submitted on: 2025-10-28 18:53:04
Comments
Log in to comment.
No comments yet.