Verified contractExactGPL-2.0-or-later
AccountLens
Address0x2c5c13e4600aabf77c1fdaa7b63d2d654ddff7c5
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 20,000 runs
- EVM version
- cancun
- License
- GPL-2.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,632,781
- Creation transaction
- 0xafc65a7c56…9048890139
13 files
- src/Lens/AccountLens.solmain19.56 KB
- lib/ethereum-vault-connector/src/interfaces/IEthereumVaultConnector.sol30.45 KB
- lib/ethereum-vault-connector/src/interfaces/IVault.sol2.13 KB
- lib/euler-price-oracle/src/interfaces/IPriceOracle.sol1.55 KB
- lib/euler-vault-kit/lib/permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- lib/euler-vault-kit/lib/permit2/src/interfaces/IEIP712.sol144 B
- lib/euler-vault-kit/src/EVault/IEVault.sol29.29 KB
- lib/euler-vault-kit/src/EVault/shared/Errors.sol1.79 KB
- lib/euler-vault-kit/src/EVault/shared/lib/RPow.sol3.5 KB
- lib/reward-streams/src/interfaces/IBalanceTracker.sol1.17 KB
- lib/reward-streams/src/interfaces/IRewardStreams.sol3.06 KB
- src/Lens/LensTypes.sol10.93 KB
- src/Lens/Utils.sol11.34 KB
src/Lens/AccountLens.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {IEVC} from "ethereum-vault-connector/interfaces/IEthereumVaultConnector.sol";
import {IPriceOracle} from "euler-price-oracle/interfaces/IPriceOracle.sol";
import {IRewardStreams} from "reward-streams/interfaces/IRewardStreams.sol";
import {IEVault} from "evk/EVault/IEVault.sol";
import {Errors} from "evk/EVault/shared/Errors.sol";
import {Utils} from "./Utils.sol";
import "./LensTypes.sol";
contract AccountLens is Utils {
function getAccountInfo(address account, address vault) public view returns (AccountInfo memory) {
AccountInfo memory result;
result.evcAccountInfo = getEVCAccountInfo(IEVault(vault).EVC(), account);
result.vaultAccountInfo = getVaultAccountInfo(account, vault);
result.accountRewardInfo = getRewardAccountInfo(account, vault);
return result;
}
function getAccountEnabledVaultsInfo(address evc, address account)
public
view
returns (AccountMultipleVaultsInfo memory)
{
AccountMultipleVaultsInfo memory result;
result.evcAccountInfo = getEVCAccountInfo(evc, account);
uint256 controllersLength = result.evcAccountInfo.enabledControllers.length;
uint256 collateralsLength = result.evcAccountInfo.enabledCollaterals.length;
uint256 counter = collateralsLength;
for (uint256 i = 0; i < controllersLength; ++i) {
if (!IEVC(evc).isCollateralEnabled(account, result.evcAccountInfo.enabledControllers[i])) {
++counter;
}
}
result.vaultAccountInfo = new VaultAccountInfo[](counter);
result.accountRewardInfo = new AccountRewardInfo[](counter);
for (uint256 i = 0; i < controllersLength; ++i) {
result.vaultAccountInfo[i] = tryGetVaultAccountInfo(account, result.evcAccountInfo.enabledControllers[i]);
result.accountRewardInfo[i] = tryGetRewardAccountInfo(account, result.evcAccountInfo.enabledControllers[i]);
}
counter = controllersLength;
for (uint256 i = 0; i < collateralsLength; ++i) {
address collateral = result.evcAccountInfo.enabledCollaterals[i];
// this used to come from getVaultAccountInfo, which asks the EVC the vault itself reports. Asking the EVC
// passed in matches the source the counting loop above uses, and still answers for a vault whose query
// failed: such a vault reports no controller, which would write past the end of the array
if (IEVC(evc).isControllerEnabled(account, collateral)) continue;
result.vaultAccountInfo[counter] = tryGetVaultAccountInfo(account, collateral);
result.accountRewardInfo[counter] = tryGetRewardAccountInfo(account, collateral);
++counter;
}
return result;
}
/// @dev Any address can be enabled as a collateral on the EVC, including one whose return data makes the queries in
/// getVaultAccountInfo revert. Isolating each vault behind an external call keeps one such collateral from taking
/// down the whole account query; the offending vault reports queryFailure and the rest still return their data.
function tryGetVaultAccountInfo(address account, address vault) public view returns (VaultAccountInfo memory) {
try this.getVaultAccountInfo(account, vault) returns (VaultAccountInfo memory info) {
return info;
} catch (bytes memory reason) {
VaultAccountInfo memory result;
result.timestamp = block.timestamp;
result.account = account;
result.vault = vault;
result.queryFailure = true;
result.queryFailureReason = reason;
result.liquidityInfo.account = account;
result.liquidityInfo.vault = vault;
result.liquidityInfo.queryFailure = true;
result.liquidityInfo.queryFailureReason = reason;
return result;
}
}
/// @dev See tryGetVaultAccountInfo.
function tryGetRewardAccountInfo(address account, address vault) public view returns (AccountRewardInfo memory) {
try this.getRewardAccountInfo(account, vault) returns (AccountRewardInfo memory info) {
return info;
} catch {
AccountRewardInfo memory result;
result.timestamp = block.timestamp;
result.account = account;
result.vault = vault;
return result;
}
}
function getEVCAccountInfo(address evc, address account) public view returns (EVCAccountInfo memory) {
EVCAccountInfo memory result;
result.timestamp = block.timestamp;
result.evc = evc;
result.account = account;
result.addressPrefix = IEVC(evc).getAddressPrefix(account);
result.owner = IEVC(evc).getAccountOwner(account);
result.isLockdownMode = IEVC(evc).isLockdownMode(result.addressPrefix);
result.isPermitDisabledMode = IEVC(evc).isPermitDisabledMode(result.addressPrefix);
result.lastAccountStatusCheckTimestamp = IEVC(evc).getLastAccountStatusCheckTimestamp(account);
result.enabledControllers = IEVC(evc).getControllers(account);
result.enabledCollaterals = IEVC(evc).getCollaterals(account);
return result;
}
function getVaultAccountInfo(address account, address vault) public view returns (VaultAccountInfo memory) {
VaultAccountInfo memory result;
result.timestamp = block.timestamp;
result.account = account;
result.vault = vault;
(bool success, bytes memory data) = vault.staticcall(abi.encodeCall(IEVault(vault).asset, ()));
if (success && data.length >= 32) {
result.asset = abi.decode(data, (address));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) = result.asset.staticcall(abi.encodeCall(IEVault(result.asset).balanceOf, (account)));
if (success && data.length >= 32) {
result.assetsAccount = abi.decode(data, (uint256));
} else {
if (!result.queryFailure) result.queryFailureReason = data;
result.queryFailure = true;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).balanceOf, (account)));
if (success && data.length >= 32) {
result.shares = abi.decode(data, (uint256));
} else {
if (!result.queryFailure) result.queryFailureReason = data;
result.queryFailure = true;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).convertToAssets, (result.shares)));
if (success && data.length >= 32) {
result.assets = abi.decode(data, (uint256));
} else {
if (!result.queryFailure) result.queryFailureReason = data;
result.queryFailure = true;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).debtOf, (account)));
// optional: vaults with no debt concept (i.e. plain ERC-4626) correctly report no borrows
if (success && data.length >= 32) {
result.borrowed = abi.decode(data, (uint256));
}
(success, data) = result.asset.staticcall(abi.encodeCall(IEVault(result.asset).allowance, (account, vault)));
if (success && data.length >= 32) {
result.assetAllowanceVault = abi.decode(data, (uint256));
} else {
if (!result.queryFailure) result.queryFailureReason = data;
result.queryFailure = true;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).permit2Address, ()));
// optional: vaults with no permit2 integration correctly report no permit2 allowances
address permit2;
if (success && data.length >= 32) {
permit2 = abi.decode(data, (address));
}
if (permit2 != address(0) && result.asset != address(0)) {
(result.assetAllowanceVaultPermit2, result.assetAllowanceExpirationVaultPermit2,) =
IAllowanceTransfer(permit2).allowance(account, result.asset, vault);
result.assetAllowancePermit2 = IEVault(result.asset).allowance(account, permit2);
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).balanceForwarderEnabled, (account)));
// optional: vaults with no balance forwarding correctly report it as disabled
if (success && data.length >= 32) {
result.balanceForwarderEnabled = abi.decode(data, (bool));
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).EVC, ()));
address evc;
if (success && data.length >= 32) {
evc = abi.decode(data, (address));
} else {
if (!result.queryFailure) result.queryFailureReason = data;
result.queryFailure = true;
}
if (evc != address(0)) {
result.isController = IEVC(evc).isControllerEnabled(account, vault);
result.isCollateral = IEVC(evc).isCollateralEnabled(account, vault);
}
result.liquidityInfo = getAccountLiquidityInfo(account, vault);
return result;
}
function getAccountLiquidityInfo(address account, address vault) public view returns (AccountLiquidityInfo memory) {
AccountLiquidityInfo memory result;
result.account = account;
result.vault = vault;
(bool success, bytes memory data) = vault.staticcall(abi.encodeCall(IEVault(vault).unitOfAccount, ()));
if (success && data.length >= 32) {
result.unitOfAccount = abi.decode(data, (address));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).accountLiquidity, (account, false)));
if (success && data.length >= 64) {
(result.collateralValueBorrowing, result.liabilityValueBorrowing) = abi.decode(data, (uint256, uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).accountLiquidity, (account, true)));
if (success && data.length >= 64) {
(result.collateralValueLiquidation, result.liabilityValueLiquidation) = abi.decode(data, (uint256, uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).accountLiquidityFull, (account, false)));
if (success && data.length >= 64) {
(result.collaterals, result.collateralValuesBorrowing,) = abi.decode(data, (address[], uint256[], uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) = vault.staticcall(abi.encodeCall(IEVault(vault).accountLiquidityFull, (account, true)));
if (success && data.length >= 64) {
(result.collaterals, result.collateralValuesLiquidation,) =
abi.decode(data, (address[], uint256[], uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
if (!result.queryFailure) {
result.collateralValuesRaw = new uint256[](result.collaterals.length);
for (uint256 i = 0; i < result.collaterals.length; ++i) {
(success, data) =
vault.staticcall(abi.encodeCall(IEVault(vault).LTVLiquidation, (result.collaterals[i])));
if (success && data.length >= 32) {
uint256 liquidationLTV = abi.decode(data, (uint16));
if (liquidationLTV != 0) {
result.collateralValuesRaw[i] =
result.collateralValuesLiquidation[i] * CONFIG_SCALE / liquidationLTV;
}
}
result.collateralValueRaw += result.collateralValuesRaw[i];
}
}
if (!result.queryFailure) {
result.timeToLiquidation = _calculateTimeToLiquidation(
vault, result.liabilityValueLiquidation, result.collaterals, result.collateralValuesLiquidation
);
}
return result;
}
function getAccountLiquidityInfoNoValidation(address account, address vault)
public
view
returns (AccountLiquidityInfo memory)
{
AccountLiquidityInfo memory result = getAccountLiquidityInfo(account, vault);
if (
!result.queryFailure
|| (bytes4(result.queryFailureReason) != Errors.E_TransientState.selector
&& bytes4(result.queryFailureReason) != Errors.E_NoLiability.selector
&& bytes4(result.queryFailureReason) != Errors.E_NotController.selector
&& bytes4(result.queryFailureReason) != Errors.E_NoPriceOracle.selector)
) return result;
result.queryFailure = false;
result.queryFailureReason = "";
result.account = account;
result.vault = vault;
result.timeToLiquidation = TTL_ERROR;
result.liabilityValueBorrowing = 0;
result.liabilityValueLiquidation = 0;
result.collateralValueBorrowing = 0;
result.collateralValueLiquidation = 0;
result.collateralValueRaw = 0;
result.unitOfAccount = IEVault(vault).unitOfAccount();
result.collaterals = IEVC(IEVault(vault).EVC()).getCollaterals(account);
result.collateralValuesBorrowing = new uint256[](result.collaterals.length);
result.collateralValuesLiquidation = new uint256[](result.collaterals.length);
result.collateralValuesRaw = new uint256[](result.collaterals.length);
address oracle = IEVault(vault).oracle();
uint256 debt = IEVault(vault).debtOf(account);
if (debt != 0) {
address asset = IEVault(vault).asset();
(bool success, bytes memory data) =
oracle.staticcall(abi.encodeCall(IPriceOracle.getQuotes, (debt, asset, result.unitOfAccount)));
if (success && data.length >= 32) {
(, result.liabilityValueBorrowing) = abi.decode(data, (uint256, uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) =
oracle.staticcall(abi.encodeCall(IPriceOracle.getQuote, (debt, asset, result.unitOfAccount)));
if (!result.queryFailure && success && data.length >= 32) {
result.liabilityValueLiquidation = abi.decode(data, (uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
}
if (result.queryFailure) return result;
for (uint256 i = 0; i < result.collaterals.length; ++i) {
address collateral = result.collaterals[i];
uint256 balance;
(bool success, bytes memory data) =
collateral.staticcall(abi.encodeCall(IEVault(collateral).balanceOf, (account)));
if (success && data.length >= 32) {
balance = abi.decode(data, (uint256));
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
if (balance == 0) continue;
(success, data) =
oracle.staticcall(abi.encodeCall(IPriceOracle.getQuote, (balance, collateral, result.unitOfAccount)));
if (success && data.length >= 32) {
result.collateralValuesRaw[i] = abi.decode(data, (uint256));
result.collateralValueRaw += result.collateralValuesRaw[i];
result.collateralValuesLiquidation[i] =
result.collateralValuesRaw[i] * IEVault(vault).LTVLiquidation(collateral) / CONFIG_SCALE;
result.collateralValueLiquidation += result.collateralValuesLiquidation[i];
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
(success, data) =
oracle.staticcall(abi.encodeCall(IPriceOracle.getQuotes, (balance, collateral, result.unitOfAccount)));
if (success && data.length >= 32) {
(uint256 collateralValue,) = abi.decode(data, (uint256, uint256));
result.collateralValuesBorrowing[i] =
collateralValue * IEVault(vault).LTVBorrow(collateral) / CONFIG_SCALE;
result.collateralValueBorrowing += result.collateralValuesBorrowing[i];
} else {
result.queryFailure = true;
result.queryFailureReason = data;
}
}
return result;
}
function getTimeToLiquidation(address account, address vault) public view returns (int256) {
address[] memory collaterals;
uint256[] memory collateralValues;
uint256 liabilityValue;
// get detailed collateral values and liability value
try IEVault(vault).accountLiquidityFull(account, true) returns (
address[] memory _collaterals, uint256[] memory _collateralValues, uint256 _liabilityValue
) {
collaterals = _collaterals;
collateralValues = _collateralValues;
liabilityValue = _liabilityValue;
} catch (bytes memory reason) {
if (bytes4(reason) != Errors.E_NoLiability.selector) return TTL_ERROR;
}
return _calculateTimeToLiquidation(vault, liabilityValue, collaterals, collateralValues);
}
function getRewardAccountInfo(address account, address vault) public view returns (AccountRewardInfo memory) {
AccountRewardInfo memory result;
result.timestamp = block.timestamp;
result.account = account;
result.vault = vault;
(bool success, bytes memory data) = vault.staticcall(abi.encodeCall(IEVault(vault).balanceTrackerAddress, ()));
if (!success || data.length < 32) {
return result;
}
result.balanceTracker = abi.decode(data, (address));
result.balanceForwarderEnabled = IEVault(vault).balanceForwarderEnabled(account);
if (result.balanceTracker == address(0)) return result;
result.balance = IRewardStreams(result.balanceTracker).balanceOf(account, vault);
address[] memory enabledRewards = IRewardStreams(result.balanceTracker).enabledRewards(account, vault);
result.enabledRewardsInfo = new EnabledRewardInfo[](enabledRewards.length);
for (uint256 i; i < enabledRewards.length; ++i) {
result.enabledRewardsInfo[i].reward = enabledRewards[i];
result.enabledRewardsInfo[i].earnedReward =
IRewardStreams(result.balanceTracker).earnedReward(account, vault, enabledRewards[i], false);
result.enabledRewardsInfo[i].earnedRewardRecentIgnored =
IRewardStreams(result.balanceTracker).earnedReward(account, vault, enabledRewards[i], true);
}
return result;
}
}
lib/ethereum-vault-connector/src/interfaces/IEthereumVaultConnector.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title IEVC
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice This interface defines the methods for the Ethereum Vault Connector.
interface IEVC {
/// @notice A struct representing a batch item.
/// @dev Each batch item represents a single operation to be performed within a checks deferred context.
struct BatchItem {
/// @notice The target contract to be called.
address targetContract;
/// @notice The account on behalf of which the operation is to be performed. msg.sender must be authorized to
/// act on behalf of this account. Must be address(0) if the target contract is the EVC itself.
address onBehalfOfAccount;
/// @notice The amount of value to be forwarded with the call. If the value is type(uint256).max, the whole
/// balance of the EVC contract will be forwarded. Must be 0 if the target contract is the EVC itself.
uint256 value;
/// @notice The encoded data which is called on the target contract.
bytes data;
}
/// @notice A struct representing the result of a batch item operation.
/// @dev Used only for simulation purposes.
struct BatchItemResult {
/// @notice A boolean indicating whether the operation was successful.
bool success;
/// @notice The result of the operation.
bytes result;
}
/// @notice A struct representing the result of the account or vault status check.
/// @dev Used only for simulation purposes.
struct StatusCheckResult {
/// @notice The address of the account or vault for which the check was performed.
address checkedAddress;
/// @notice A boolean indicating whether the status of the account or vault is valid.
bool isValid;
/// @notice The result of the check.
bytes result;
}
/// @notice Returns current raw execution context.
/// @dev When checks in progress, on behalf of account is always address(0).
/// @return context Current raw execution context.
function getRawExecutionContext() external view returns (uint256 context);
/// @notice Returns an account on behalf of which the operation is being executed at the moment and whether the
/// controllerToCheck is an enabled controller for that account.
/// @dev This function should only be used by external smart contracts if msg.sender is the EVC. Otherwise, the
/// account address returned must not be trusted.
/// @dev When checks in progress, on behalf of account is always address(0). When address is zero, the function
/// reverts to protect the consumer from ever relying on the on behalf of account address which is in its default
/// state.
/// @param controllerToCheck The address of the controller for which it is checked whether it is an enabled
/// controller for the account on behalf of which the operation is being executed at the moment.
/// @return onBehalfOfAccount An account that has been authenticated and on behalf of which the operation is being
/// executed at the moment.
/// @return controllerEnabled A boolean value that indicates whether controllerToCheck is an enabled controller for
/// the account on behalf of which the operation is being executed at the moment. Always false if controllerToCheck
/// is address(0).
function getCurrentOnBehalfOfAccount(address controllerToCheck)
external
view
returns (address onBehalfOfAccount, bool controllerEnabled);
/// @notice Checks if checks are deferred.
/// @return A boolean indicating whether checks are deferred.
function areChecksDeferred() external view returns (bool);
/// @notice Checks if checks are in progress.
/// @return A boolean indicating whether checks are in progress.
function areChecksInProgress() external view returns (bool);
/// @notice Checks if control collateral is in progress.
/// @return A boolean indicating whether control collateral is in progress.
function isControlCollateralInProgress() external view returns (bool);
/// @notice Checks if an operator is authenticated.
/// @return A boolean indicating whether an operator is authenticated.
function isOperatorAuthenticated() external view returns (bool);
/// @notice Checks if a simulation is in progress.
/// @return A boolean indicating whether a simulation is in progress.
function isSimulationInProgress() external view returns (bool);
/// @notice Checks whether the specified account and the other account have the same owner.
/// @dev The function is used to check whether one account is authorized to perform operations on behalf of the
/// other. Accounts are considered to have a common owner if they share the first 19 bytes of their address.
/// @param account The address of the account that is being checked.
/// @param otherAccount The address of the other account that is being checked.
/// @return A boolean flag that indicates whether the accounts have the same owner.
function haveCommonOwner(address account, address otherAccount) external pure returns (bool);
/// @notice Returns the address prefix of the specified account.
/// @dev The address prefix is the first 19 bytes of the account address.
/// @param account The address of the account whose address prefix is being retrieved.
/// @return A bytes19 value that represents the address prefix of the account.
function getAddressPrefix(address account) external pure returns (bytes19);
/// @notice Returns the owner for the specified account.
/// @dev The function returns address(0) if the owner is not registered. Registration of the owner happens on the
/// initial
/// interaction with the EVC that requires authentication of an owner.
/// @param account The address of the account whose owner is being retrieved.
/// @return owner The address of the account owner. An account owner is an EOA/smart contract which address matches
/// the first 19 bytes of the account address.
function getAccountOwner(address account) external view returns (address);
/// @notice Checks if lockdown mode is enabled for a given address prefix.
/// @param addressPrefix The address prefix to check for lockdown mode status.
/// @return A boolean indicating whether lockdown mode is enabled.
function isLockdownMode(bytes19 addressPrefix) external view returns (bool);
/// @notice Checks if permit functionality is disabled for a given address prefix.
/// @param addressPrefix The address prefix to check for permit functionality status.
/// @return A boolean indicating whether permit functionality is disabled.
function isPermitDisabledMode(bytes19 addressPrefix) external view returns (bool);
/// @notice Returns the current nonce for a given address prefix and nonce namespace.
/// @dev Each nonce namespace provides 256 bit nonce that has to be used sequentially. There's no requirement to use
/// all the nonces for a given nonce namespace before moving to the next one which allows to use permit messages in
/// a non-sequential manner.
/// @param addressPrefix The address prefix for which the nonce is being retrieved.
/// @param nonceNamespace The nonce namespace for which the nonce is being retrieved.
/// @return nonce The current nonce for the given address prefix and nonce namespace.
function getNonce(bytes19 addressPrefix, uint256 nonceNamespace) external view returns (uint256 nonce);
/// @notice Returns the bit field for a given address prefix and operator.
/// @dev The bit field is used to store information about authorized operators for a given address prefix. Each bit
/// in the bit field corresponds to one account belonging to the same owner. If the bit is set, the operator is
/// authorized for the account.
/// @param addressPrefix The address prefix for which the bit field is being retrieved.
/// @param operator The address of the operator for which the bit field is being retrieved.
/// @return operatorBitField The bit field for the given address prefix and operator. The bit field defines which
/// accounts the operator is authorized for. It is a 256-position binary array like 0...010...0, marking the account
/// positionally in a uint256. The position in the bit field corresponds to the account ID (0-255), where 0 is the
/// owner account's ID.
function getOperator(bytes19 addressPrefix, address operator) external view returns (uint256 operatorBitField);
/// @notice Returns whether a given operator has been authorized for a given account.
/// @param account The address of the account whose operator is being checked.
/// @param operator The address of the operator that is being checked.
/// @return authorized A boolean value that indicates whether the operator is authorized for the account.
function isAccountOperatorAuthorized(address account, address operator) external view returns (bool authorized);
/// @notice Enables or disables lockdown mode for a given address prefix.
/// @dev This function can only be called by the owner of the address prefix. To disable this mode, the EVC
/// must be called directly. It is not possible to disable this mode by using checks-deferrable call or
/// permit message.
/// @param addressPrefix The address prefix for which the lockdown mode is being set.
/// @param enabled A boolean indicating whether to enable or disable lockdown mode.
function setLockdownMode(bytes19 addressPrefix, bool enabled) external payable;
/// @notice Enables or disables permit functionality for a given address prefix.
/// @dev This function can only be called by the owner of the address prefix. To disable this mode, the EVC
/// must be called directly. It is not possible to disable this mode by using checks-deferrable call or (by
/// definition) permit message. To support permit functionality by default, note that the logic was inverted here. To
/// disable the permit functionality, one must pass true as the second argument. To enable the permit
/// functionality, one must pass false as the second argument.
/// @param addressPrefix The address prefix for which the permit functionality is being set.
/// @param enabled A boolean indicating whether to enable or disable the disable-permit mode.
function setPermitDisabledMode(bytes19 addressPrefix, bool enabled) external payable;
/// @notice Sets the nonce for a given address prefix and nonce namespace.
/// @dev This function can only be called by the owner of the address prefix. Each nonce namespace provides a 256
/// bit nonce that has to be used sequentially. There's no requirement to use all the nonces for a given nonce
/// namespace before moving to the next one which allows the use of permit messages in a non-sequential manner. To
/// invalidate signed permit messages, set the nonce for a given nonce namespace accordingly. To invalidate all the
/// permit messages for a given nonce namespace, set the nonce to type(uint).max.
/// @param addressPrefix The address prefix for which the nonce is being set.
/// @param nonceNamespace The nonce namespace for which the nonce is being set.
/// @param nonce The new nonce for the given address prefix and nonce namespace.
function setNonce(bytes19 addressPrefix, uint256 nonceNamespace, uint256 nonce) external payable;
/// @notice Sets the bit field for a given address prefix and operator.
/// @dev This function can only be called by the owner of the address prefix. Each bit in the bit field corresponds
/// to one account belonging to the same owner. If the bit is set, the operator is authorized for the account.
/// @param addressPrefix The address prefix for which the bit field is being set.
/// @param operator The address of the operator for which the bit field is being set. Can neither be the EVC address
/// nor an address belonging to the same address prefix.
/// @param operatorBitField The new bit field for the given address prefix and operator. Reverts if the provided
/// value is equal to the currently stored value.
function setOperator(bytes19 addressPrefix, address operator, uint256 operatorBitField) external payable;
/// @notice Authorizes or deauthorizes an operator for the account.
/// @dev Only the owner or authorized operator of the account can call this function. An operator is an address that
/// can perform actions for an account on behalf of the owner. If it's an operator calling this function, it can
/// only deauthorize itself.
/// @param account The address of the account whose operator is being set or unset.
/// @param operator The address of the operator that is being installed or uninstalled. Can neither be the EVC
/// address nor an address belonging to the same owner as the account.
/// @param authorized A boolean value that indicates whether the operator is being authorized or deauthorized.
/// Reverts if the provided value is equal to the currently stored value.
function setAccountOperator(address account, address operator, bool authorized) external payable;
/// @notice Returns an array of collaterals enabled for an account.
/// @dev A collateral is a vault for which an account's balances are under the control of the currently enabled
/// controller vault.
/// @param account The address of the account whose collaterals are being queried.
/// @return An array of addresses that are enabled collaterals for the account.
function getCollaterals(address account) external view returns (address[] memory);
/// @notice Returns whether a collateral is enabled for an account.
/// @dev A collateral is a vault for which account's balances are under the control of the currently enabled
/// controller vault.
/// @param account The address of the account that is being checked.
/// @param vault The address of the collateral that is being checked.
/// @return A boolean value that indicates whether the vault is an enabled collateral for the account or not.
function isCollateralEnabled(address account, address vault) external view returns (bool);
/// @notice Enables a collateral for an account.
/// @dev A collaterals is a vault for which account's balances are under the control of the currently enabled
/// controller vault. Only the owner or an operator of the account can call this function. Unless it's a duplicate,
/// the collateral is added to the end of the array. There can be at most 10 unique collaterals enabled at a time.
/// Account status checks are performed.
/// @param account The account address for which the collateral is being enabled.
/// @param vault The address being enabled as a collateral.
function enableCollateral(address account, address vault) external payable;
/// @notice Disables a collateral for an account.
/// @dev This function does not preserve the order of collaterals in the array obtained using the getCollaterals
/// function; the order may change. A collateral is a vault for which account’s balances are under the control of
/// the currently enabled controller vault. Only the owner or an operator of the account can call this function.
/// Disabling a collateral might change the order of collaterals in the array obtained using getCollaterals
/// function. Account status checks are performed.
/// @param account The account address for which the collateral is being disabled.
/// @param vault The address of a collateral being disabled.
function disableCollateral(address account, address vault) external payable;
/// @notice Swaps the position of two collaterals so that they appear switched in the array of collaterals for a
/// given account obtained by calling getCollaterals function.
/// @dev A collateral is a vault for which account’s balances are under the control of the currently enabled
/// controller vault. Only the owner or an operator of the account can call this function. The order of collaterals
/// can be changed by specifying the indices of the two collaterals to be swapped. Indices are zero-based and must
/// be in the range of 0 to the number of collaterals minus 1. index1 must be lower than index2. Account status
/// checks are performed.
/// @param account The address of the account for which the collaterals are being reordered.
/// @param index1 The index of the first collateral to be swapped.
/// @param index2 The index of the second collateral to be swapped.
function reorderCollaterals(address account, uint8 index1, uint8 index2) external payable;
/// @notice Returns an array of enabled controllers for an account.
/// @dev A controller is a vault that has been chosen for an account to have special control over the account's
/// balances in enabled collaterals vaults. A user can have multiple controllers during a call execution, but at
/// most one can be selected when the account status check is performed.
/// @param account The address of the account whose controllers are being queried.
/// @return An array of addresses that are the enabled controllers for the account.
function getControllers(address account) external view returns (address[] memory);
/// @notice Returns whether a controller is enabled for an account.
/// @dev A controller is a vault that has been chosen for an account to have special control over account’s
/// balances in the enabled collaterals vaults.
/// @param account The address of the account that is being checked.
/// @param vault The address of the controller that is being checked.
/// @return A boolean value that indicates whether the vault is enabled controller for the account or not.
function isControllerEnabled(address account, address vault) external view returns (bool);
/// @notice Enables a controller for an account.
/// @dev A controller is a vault that has been chosen for an account to have special control over account’s
/// balances in the enabled collaterals vaults. Only the owner or an operator of the account can call this function.
/// Unless it's a duplicate, the controller is added to the end of the array. Transiently, there can be at most 10
/// unique controllers enabled at a time, but at most one can be enabled after the outermost checks-deferrable
/// call concludes. Account status checks are performed.
/// @param account The address for which the controller is being enabled.
/// @param vault The address of the controller being enabled.
function enableController(address account, address vault) external payable;
/// @notice Disables a controller for an account.
/// @dev A controller is a vault that has been chosen for an account to have special control over account’s
/// balances in the enabled collaterals vaults. Only the vault itself can call this function. Disabling a controller
/// might change the order of controllers in the array obtained using getControllers function. Account status checks
/// are performed.
/// @param account The address for which the calling controller is being disabled.
function disableController(address account) external payable;
/// @notice Executes signed arbitrary data by self-calling into the EVC.
/// @dev Low-level call function is used to execute the arbitrary data signed by the owner or the operator on the
/// EVC contract. During that call, EVC becomes msg.sender.
/// @param signer The address signing the permit message (ECDSA) or verifying the permit message signature
/// (ERC-1271). It's also the owner or the operator of all the accounts for which authentication will be needed
/// during the execution of the arbitrary data call.
/// @param sender The address of the msg.sender which is expected to execute the data signed by the signer. If
/// address(0) is passed, the msg.sender is ignored.
/// @param nonceNamespace The nonce namespace for which the nonce is being used.
/// @param nonce The nonce for the given account and nonce namespace. A valid nonce value is considered to be the
/// value currently stored and can take any value between 0 and type(uint256).max - 1.
/// @param deadline The timestamp after which the permit is considered expired.
/// @param value The amount of value to be forwarded with the call. If the value is type(uint256).max, the whole
/// balance of the EVC contract will be forwarded.
/// @param data The encoded data which is self-called on the EVC contract.
/// @param signature The signature of the data signed by the signer.
function permit(
address signer,
address sender,
uint256 nonceNamespace,
uint256 nonce,
uint256 deadline,
uint256 value,
bytes calldata data,
bytes calldata signature
) external payable;
/// @notice Calls into a target contract as per data encoded.
/// @dev This function defers the account and vault status checks (it's a checks-deferrable call). If the outermost
/// call ends, the account and vault status checks are performed.
/// @dev This function can be used to interact with any contract while checks are deferred. If the target contract
/// is msg.sender, msg.sender is called back with the calldata provided and the context set up according to the
/// account provided. If the target contract is not msg.sender, only the owner or the operator of the account
/// provided can call this function.
/// @dev This function can be used to recover the remaining value from the EVC contract.
/// @param targetContract The address of the contract to be called.
/// @param onBehalfOfAccount If the target contract is msg.sender, the address of the account which will be set
/// in the context. It assumes msg.sender has authenticated the account themselves. If the target contract is
/// not msg.sender, the address of the account for which it is checked whether msg.sender is authorized to act
/// on behalf of.
/// @param value The amount of value to be forwarded with the call. If the value is type(uint256).max, the whole
/// balance of the EVC contract will be forwarded.
/// @param data The encoded data which is called on the target contract.
/// @return result The result of the call.
function call(
address targetContract,
address onBehalfOfAccount,
uint256 value,
bytes calldata data
) external payable returns (bytes memory result);
/// @notice For a given account, calls into one of the enabled collateral vaults from the currently enabled
/// controller vault as per data encoded.
/// @dev This function defers the account and vault status checks (it's a checks-deferrable call). If the outermost
/// call ends, the account and vault status checks are performed.
/// @dev This function can be used to interact with any contract while checks are deferred as long as the contract
/// is enabled as a collateral of the account and the msg.sender is the only enabled controller of the account.
/// @param targetCollateral The collateral address to be called.
/// @param onBehalfOfAccount The address of the account for which it is checked whether msg.sender is authorized to
/// act on behalf.
/// @param value The amount of value to be forwarded with the call. If the value is type(uint256).max, the whole
/// balance of the EVC contract will be forwarded.
/// @param data The encoded data which is called on the target collateral.
/// @return result The result of the call.
function controlCollateral(
address targetCollateral,
address onBehalfOfAccount,
uint256 value,
bytes calldata data
) external payable returns (bytes memory result);
/// @notice Executes multiple calls into the target contracts while checks deferred as per batch items provided.
/// @dev This function defers the account and vault status checks (it's a checks-deferrable call). If the outermost
/// call ends, the account and vault status checks are performed.
/// @dev The authentication rules for each batch item are the same as for the call function.
/// @param items An array of batch items to be executed.
function batch(BatchItem[] calldata items) external payable;
/// @notice Executes multiple calls into the target contracts while checks deferred as per batch items provided.
/// @dev This function always reverts as it's only used for simulation purposes. This function cannot be called
/// within a checks-deferrable call.
/// @param items An array of batch items to be executed.
function batchRevert(BatchItem[] calldata items) external payable;
/// @notice Executes multiple calls into the target contracts while checks deferred as per batch items provided.
/// @dev This function does not modify state and should only be used for simulation purposes. This function cannot
/// be called within a checks-deferrable call.
/// @param items An array of batch items to be executed.
/// @return batchItemsResult An array of batch item results for each item.
/// @return accountsStatusCheckResult An array of account status check results for each account.
/// @return vaultsStatusCheckResult An array of vault status check results for each vault.
function batchSimulation(BatchItem[] calldata items)
external
payable
returns (
BatchItemResult[] memory batchItemsResult,
StatusCheckResult[] memory accountsStatusCheckResult,
StatusCheckResult[] memory vaultsStatusCheckResult
);
/// @notice Retrieves the timestamp of the last successful account status check performed for a specific account.
/// @dev This function reverts if the checks are in progress.
/// @dev The account status check is considered to be successful if it calls into the selected controller vault and
/// obtains expected magic value. This timestamp does not change if the account status is considered valid when no
/// controller enabled. When consuming, one might need to ensure that the account status check is not deferred at
/// the moment.
/// @param account The address of the account for which the last status check timestamp is being queried.
/// @return The timestamp of the last status check as a uint256.
function getLastAccountStatusCheckTimestamp(address account) external view returns (uint256);
/// @notice Checks whether the status check is deferred for a given account.
/// @dev This function reverts if the checks are in progress.
/// @param account The address of the account for which it is checked whether the status check is deferred.
/// @return A boolean flag that indicates whether the status check is deferred or not.
function isAccountStatusCheckDeferred(address account) external view returns (bool);
/// @notice Checks the status of an account and reverts if it is not valid.
/// @dev If checks deferred, the account is added to the set of accounts to be checked at the end of the outermost
/// checks-deferrable call. There can be at most 10 unique accounts added to the set at a time. Account status
/// check is performed by calling into the selected controller vault and passing the array of currently enabled
/// collaterals. If controller is not selected, the account is always considered valid.
/// @param account The address of the account to be checked.
function requireAccountStatusCheck(address account) external payable;
/// @notice Forgives previously deferred account status check.
/// @dev Account address is removed from the set of addresses for which status checks are deferred. This function
/// can only be called by the currently enabled controller of a given account. Depending on the vault
/// implementation, may be needed in the liquidation flow.
/// @param account The address of the account for which the status check is forgiven.
function forgiveAccountStatusCheck(address account) external payable;
/// @notice Checks whether the status check is deferred for a given vault.
/// @dev This function reverts if the checks are in progress.
/// @param vault The address of the vault for which it is checked whether the status check is deferred.
/// @return A boolean flag that indicates whether the status check is deferred or not.
function isVaultStatusCheckDeferred(address vault) external view returns (bool);
/// @notice Checks the status of a vault and reverts if it is not valid.
/// @dev If checks deferred, the vault is added to the set of vaults to be checked at the end of the outermost
/// checks-deferrable call. There can be at most 10 unique vaults added to the set at a time. This function can
/// only be called by the vault itself.
function requireVaultStatusCheck() external payable;
/// @notice Forgives previously deferred vault status check.
/// @dev Vault address is removed from the set of addresses for which status checks are deferred. This function can
/// only be called by the vault itself.
function forgiveVaultStatusCheck() external payable;
/// @notice Checks the status of an account and a vault and reverts if it is not valid.
/// @dev If checks deferred, the account and the vault are added to the respective sets of accounts and vaults to be
/// checked at the end of the outermost checks-deferrable call. Account status check is performed by calling into
/// selected controller vault and passing the array of currently enabled collaterals. If controller is not selected,
/// the account is always considered valid. This function can only be called by the vault itself.
/// @param account The address of the account to be checked.
function requireAccountAndVaultStatusCheck(address account) external payable;
}
lib/ethereum-vault-connector/src/interfaces/IVault.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title IVault
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice This interface defines the methods for the Vault for the purpose of integration with the Ethereum Vault
/// Connector.
interface IVault {
/// @notice Disables a controller (this vault) for the authenticated account.
/// @dev A controller is a vault that has been chosen for an account to have special control over account’s
/// balances in the enabled collaterals vaults. User calls this function in order for the vault to disable itself
/// for the account if the conditions are met (i.e. user has repaid debt in full). If the conditions are not met,
/// the function reverts.
function disableController() external;
/// @notice Checks the status of an account.
/// @dev This function must only deliberately revert if the account status is invalid. If this function reverts due
/// to any other reason, it may render the account unusable with possibly no way to recover funds.
/// @param account The address of the account to be checked.
/// @param collaterals The array of enabled collateral addresses to be considered for the account status check.
/// @return magicValue Must return the bytes4 magic value 0xb168c58f (which is a selector of this function) when
/// account status is valid, or revert otherwise.
function checkAccountStatus(
address account,
address[] calldata collaterals
) external view returns (bytes4 magicValue);
/// @notice Checks the status of the vault.
/// @dev This function must only deliberately revert if the vault status is invalid. If this function reverts due to
/// any other reason, it may render some accounts unusable with possibly no way to recover funds.
/// @return magicValue Must return the bytes4 magic value 0x4b3d1223 (which is a selector of this function) when
/// account status is valid, or revert otherwise.
function checkVaultStatus() external returns (bytes4 magicValue);
}
lib/euler-price-oracle/src/interfaces/IPriceOracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title IPriceOracle
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Common PriceOracle interface.
interface IPriceOracle {
/// @notice Get the name of the oracle.
/// @return The name of the oracle.
function name() external view returns (string memory);
/// @notice One-sided price: How much quote token you would get for inAmount of base token, assuming no price spread.
/// @param inAmount The amount of `base` to convert.
/// @param base The token that is being priced.
/// @param quote The token that is the unit of account.
/// @return outAmount The amount of `quote` that is equivalent to `inAmount` of `base`.
function getQuote(uint256 inAmount, address base, address quote) external view returns (uint256 outAmount);
/// @notice Two-sided price: How much quote token you would get/spend for selling/buying inAmount of base token.
/// @param inAmount The amount of `base` to convert.
/// @param base The token that is being priced.
/// @param quote The token that is the unit of account.
/// @return bidOutAmount The amount of `quote` you would get for selling `inAmount` of `base`.
/// @return askOutAmount The amount of `quote` you would spend for buying `inAmount` of `base`.
function getQuotes(uint256 inAmount, address base, address quote)
external
view
returns (uint256 bidOutAmount, uint256 askOutAmount);
}
lib/euler-vault-kit/lib/permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
lib/euler-vault-kit/lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/euler-vault-kit/src/EVault/IEVault.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import {IVault as IEVCVault} from "ethereum-vault-connector/interfaces/IVault.sol";
// Full interface of EVault and all it's modules
/// @title IInitialize
/// @notice Interface of the initialization module of EVault
interface IInitialize {
/// @notice Initialization of the newly deployed proxy contract
/// @param proxyCreator Account which created the proxy or should be the initial governor
function initialize(address proxyCreator) external;
}
/// @title IERC20
/// @notice Interface of the EVault's Initialize module
interface IERC20 {
/// @notice Vault share token (eToken) name, ie "Euler Vault: DAI"
/// @return The name of the eToken
function name() external view returns (string memory);
/// @notice Vault share token (eToken) symbol, ie "eDAI"
/// @return The symbol of the eToken
function symbol() external view returns (string memory);
/// @notice Decimals, the same as the asset's or 18 if the asset doesn't implement `decimals()`
/// @return The decimals of the eToken
function decimals() external view returns (uint8);
/// @notice Sum of all eToken balances
/// @return The total supply of the eToken
function totalSupply() external view returns (uint256);
/// @notice Balance of a particular account, in eTokens
/// @param account Address to query
/// @return The balance of the account
function balanceOf(address account) external view returns (uint256);
/// @notice Retrieve the current allowance
/// @param holder The account holding the eTokens
/// @param spender Trusted address
/// @return The allowance from holder for spender
function allowance(address holder, address spender) external view returns (uint256);
/// @notice Transfer eTokens to another address
/// @param to Recipient account
/// @param amount In shares.
/// @return True if transfer succeeded
function transfer(address to, uint256 amount) external returns (bool);
/// @notice Transfer eTokens from one address to another
/// @param from This address must've approved the to address
/// @param to Recipient account
/// @param amount In shares
/// @return True if transfer succeeded
function transferFrom(address from, address to, uint256 amount) external returns (bool);
/// @notice Allow spender to access an amount of your eTokens
/// @param spender Trusted address
/// @param amount Use max uint for "infinite" allowance
/// @return True if approval succeeded
function approve(address spender, uint256 amount) external returns (bool);
}
/// @title IToken
/// @notice Interface of the EVault's Token module
interface IToken is IERC20 {
/// @notice Transfer the full eToken balance of an address to another
/// @param from This address must've approved the to address
/// @param to Recipient account
/// @return True if transfer succeeded
function transferFromMax(address from, address to) external returns (bool);
}
/// @title IERC4626
/// @notice Interface of an ERC4626 vault
interface IERC4626 {
/// @notice Vault's underlying asset
/// @return The vault's underlying asset
function asset() external view returns (address);
/// @notice Total amount of managed assets, cash and borrows
/// @return The total amount of assets
function totalAssets() external view returns (uint256);
/// @notice Calculate amount of assets corresponding to the requested shares amount
/// @param shares Amount of shares to convert
/// @return The amount of assets
function convertToAssets(uint256 shares) external view returns (uint256);
/// @notice Calculate amount of shares corresponding to the requested assets amount
/// @param assets Amount of assets to convert
/// @return The amount of shares
function convertToShares(uint256 assets) external view returns (uint256);
/// @notice Fetch the maximum amount of assets a user can deposit
/// @param account Address to query
/// @return The max amount of assets the account can deposit
function maxDeposit(address account) external view returns (uint256);
/// @notice Calculate an amount of shares that would be created by depositing assets
/// @param assets Amount of assets deposited
/// @return Amount of shares received
function previewDeposit(uint256 assets) external view returns (uint256);
/// @notice Fetch the maximum amount of shares a user can mint
/// @param account Address to query
/// @return The max amount of shares the account can mint
function maxMint(address account) external view returns (uint256);
/// @notice Calculate an amount of assets that would be required to mint requested amount of shares
/// @param shares Amount of shares to be minted
/// @return Required amount of assets
function previewMint(uint256 shares) external view returns (uint256);
/// @notice Fetch the maximum amount of assets a user is allowed to withdraw
/// @param owner Account holding the shares
/// @return The maximum amount of assets the owner is allowed to withdraw
function maxWithdraw(address owner) external view returns (uint256);
/// @notice Calculate the amount of shares that will be burned when withdrawing requested amount of assets
/// @param assets Amount of assets withdrawn
/// @return Amount of shares burned
function previewWithdraw(uint256 assets) external view returns (uint256);
/// @notice Fetch the maximum amount of shares a user is allowed to redeem for assets
/// @param owner Account holding the shares
/// @return The maximum amount of shares the owner is allowed to redeem
function maxRedeem(address owner) external view returns (uint256);
/// @notice Calculate the amount of assets that will be transferred when redeeming requested amount of shares
/// @param shares Amount of shares redeemed
/// @return Amount of assets transferred
function previewRedeem(uint256 shares) external view returns (uint256);
/// @notice Transfer requested amount of underlying tokens from sender to the vault pool in return for shares
/// @param amount Amount of assets to deposit (use max uint256 for full underlying token balance)
/// @param receiver An account to receive the shares
/// @return Amount of shares minted
/// @dev Deposit will round down the amount of assets that are converted to shares. To prevent losses consider using
/// mint instead.
function deposit(uint256 amount, address receiver) external returns (uint256);
/// @notice Transfer underlying tokens from sender to the vault pool in return for requested amount of shares
/// @param amount Amount of shares to be minted
/// @param receiver An account to receive the shares
/// @return Amount of assets deposited
function mint(uint256 amount, address receiver) external returns (uint256);
/// @notice Transfer requested amount of underlying tokens from the vault and decrease account's shares balance
/// @param amount Amount of assets to withdraw
/// @param receiver Account to receive the withdrawn assets
/// @param owner Account holding the shares to burn
/// @return Amount of shares burned
function withdraw(uint256 amount, address receiver, address owner) external returns (uint256);
/// @notice Burn requested shares and transfer corresponding underlying tokens from the vault to the receiver
/// @param amount Amount of shares to burn (use max uint256 to burn full owner balance)
/// @param receiver Account to receive the withdrawn assets
/// @param owner Account holding the shares to burn.
/// @return Amount of assets transferred
function redeem(uint256 amount, address receiver, address owner) external returns (uint256);
}
/// @title IVault
/// @notice Interface of the EVault's Vault module
interface IVault is IERC4626 {
/// @notice Balance of the fees accumulator, in shares
/// @return The accumulated fees in shares
function accumulatedFees() external view returns (uint256);
/// @notice Balance of the fees accumulator, in underlying units
/// @return The accumulated fees in asset units
function accumulatedFeesAssets() external view returns (uint256);
/// @notice Address of the original vault creator
/// @return The address of the creator
function creator() external view returns (address);
/// @notice Creates shares for the receiver, from excess asset balances of the vault (not accounted for in `cash`)
/// @param amount Amount of assets to claim (use max uint256 to claim all available assets)
/// @param receiver An account to receive the shares
/// @return Amount of shares minted
/// @dev Could be used as an alternative deposit flow in certain scenarios. E.g. swap directly to the vault, call
/// `skim` to claim deposit.
function skim(uint256 amount, address receiver) external returns (uint256);
}
/// @title IBorrowing
/// @notice Interface of the EVault's Borrowing module
interface IBorrowing {
/// @notice Sum of all outstanding debts, in underlying units (increases as interest is accrued)
/// @return The total borrows in asset units
function totalBorrows() external view returns (uint256);
/// @notice Sum of all outstanding debts, in underlying units scaled up by shifting
/// INTERNAL_DEBT_PRECISION_SHIFT bits
/// @return The total borrows in internal debt precision
function totalBorrowsExact() external view returns (uint256);
/// @notice Balance of vault assets as tracked by deposits/withdrawals and borrows/repays
/// @return The amount of assets the vault tracks as current direct holdings
function cash() external view returns (uint256);
/// @notice Debt owed by a particular account, in underlying units
/// @param account Address to query
/// @return The debt of the account in asset units
function debtOf(address account) external view returns (uint256);
/// @notice Debt owed by a particular account, in underlying units scaled up by shifting
/// INTERNAL_DEBT_PRECISION_SHIFT bits
/// @param account Address to query
/// @return The debt of the account in internal precision
function debtOfExact(address account) external view returns (uint256);
/// @notice Retrieves the current interest rate for an asset
/// @return The interest rate in yield-per-second, scaled by 10**27
function interestRate() external view returns (uint256);
/// @notice Retrieves the current interest rate accumulator for an asset
/// @return An opaque accumulator that increases as interest is accrued
function interestAccumulator() external view returns (uint256);
/// @notice Returns an address of the sidecar DToken
/// @return The address of the DToken
function dToken() external view returns (address);
/// @notice Transfer underlying tokens from the vault to the sender, and increase sender's debt
/// @param amount Amount of assets to borrow (use max uint256 for all available tokens)
/// @param receiver Account receiving the borrowed tokens
/// @return Amount of assets borrowed
function borrow(uint256 amount, address receiver) external returns (uint256);
/// @notice Transfer underlying tokens from the sender to the vault, and decrease receiver's debt
/// @param amount Amount of debt to repay in assets (use max uint256 for full debt)
/// @param receiver Account holding the debt to be repaid
/// @return Amount of assets repaid
function repay(uint256 amount, address receiver) external returns (uint256);
/// @notice Pay off liability with shares ("self-repay")
/// @param amount In asset units (use max uint256 to repay the debt in full or up to the available deposit)
/// @param receiver Account to remove debt from by burning sender's shares
/// @return shares Amount of shares burned
/// @return debt Amount of debt removed in assets
/// @dev Equivalent to withdrawing and repaying, but no assets are needed to be present in the vault
/// @dev Contrary to a regular `repay`, if account is unhealthy, the repay amount must bring the account back to
/// health, or the operation will revert during account status check
function repayWithShares(uint256 amount, address receiver) external returns (uint256 shares, uint256 debt);
/// @notice Take over debt from another account
/// @param amount Amount of debt in asset units (use max uint256 for all the account's debt)
/// @param from Account to pull the debt from
/// @dev Due to internal debt precision accounting, the liability reported on either or both accounts after
/// calling `pullDebt` may not match the `amount` requested precisely
function pullDebt(uint256 amount, address from) external;
/// @notice Request a flash-loan. A onFlashLoan() callback in msg.sender will be invoked, which must repay the loan
/// to the main Euler address prior to returning.
/// @param amount In asset units
/// @param data Passed through to the onFlashLoan() callback, so contracts don't need to store transient data in
/// storage
function flashLoan(uint256 amount, bytes calldata data) external;
/// @notice Updates interest accumulator and totalBorrows, credits reserves, re-targets interest rate, and logs
/// vault status
function touch() external;
}
/// @title ILiquidation
/// @notice Interface of the EVault's Liquidation module
interface ILiquidation {
/// @notice Checks to see if a liquidation would be profitable, without actually doing anything
/// @param liquidator Address that will initiate the liquidation
/// @param violator Address that may be in collateral violation
/// @param collateral Collateral which is to be seized
/// @return maxRepay Max amount of debt that can be repaid, in asset units
/// @return maxYield Yield in collateral corresponding to max allowed amount of debt to be repaid, in collateral
/// balance (shares for vaults)
function checkLiquidation(address liquidator, address violator, address collateral)
external
view
returns (uint256 maxRepay, uint256 maxYield);
/// @notice Attempts to perform a liquidation
/// @param violator Address that may be in collateral violation
/// @param collateral Collateral which is to be seized
/// @param repayAssets The amount of underlying debt to be transferred from violator to sender, in asset units (use
/// max uint256 to repay the maximum possible amount). Meant as slippage check together with `minYieldBalance`
/// @param minYieldBalance The minimum acceptable amount of collateral to be transferred from violator to sender, in
/// collateral balance units (shares for vaults). Meant as slippage check together with `repayAssets`
/// @dev If `repayAssets` is set to max uint256 it is assumed the caller will perform their own slippage checks to
/// make sure they are not taking on too much debt. This option is mainly meant for smart contract liquidators
function liquidate(address violator, address collateral, uint256 repayAssets, uint256 minYieldBalance) external;
}
/// @title IRiskManager
/// @notice Interface of the EVault's RiskManager module
interface IRiskManager is IEVCVault {
/// @notice Retrieve account's total liquidity
/// @param account Account holding debt in this vault
/// @param liquidation Flag to indicate if the calculation should be performed in liquidation vs account status
/// check mode, where different LTV values might apply.
/// @return collateralValue Total risk adjusted value of all collaterals in unit of account
/// @return liabilityValue Value of debt in unit of account
function accountLiquidity(address account, bool liquidation)
external
view
returns (uint256 collateralValue, uint256 liabilityValue);
/// @notice Retrieve account's liquidity per collateral
/// @param account Account holding debt in this vault
/// @param liquidation Flag to indicate if the calculation should be performed in liquidation vs account status
/// check mode, where different LTV values might apply.
/// @return collaterals Array of collaterals enabled
/// @return collateralValues Array of risk adjusted collateral values corresponding to items in collaterals array.
/// In unit of account
/// @return liabilityValue Value of debt in unit of account
function accountLiquidityFull(address account, bool liquidation)
external
view
returns (address[] memory collaterals, uint256[] memory collateralValues, uint256 liabilityValue);
/// @notice Release control of the account on EVC if no outstanding debt is present
function disableController() external;
/// @notice Checks the status of an account and reverts if account is not healthy
/// @param account The address of the account to be checked
/// @return magicValue Must return the bytes4 magic value 0xb168c58f (which is a selector of this function) when
/// account status is valid, or revert otherwise.
/// @dev Only callable by EVC during status checks
function checkAccountStatus(address account, address[] calldata collaterals) external view returns (bytes4);
/// @notice Checks the status of the vault and reverts if caps are exceeded
/// @return magicValue Must return the bytes4 magic value 0x4b3d1223 (which is a selector of this function) when
/// account status is valid, or revert otherwise.
/// @dev Only callable by EVC during status checks
function checkVaultStatus() external returns (bytes4);
}
/// @title IBalanceForwarder
/// @notice Interface of the EVault's BalanceForwarder module
interface IBalanceForwarder {
/// @notice Retrieve the address of rewards contract, tracking changes in account's balances
/// @return The balance tracker address
function balanceTrackerAddress() external view returns (address);
/// @notice Retrieves boolean indicating if the account opted in to forward balance changes to the rewards contract
/// @param account Address to query
/// @return True if balance forwarder is enabled
function balanceForwarderEnabled(address account) external view returns (bool);
/// @notice Enables balance forwarding for the authenticated account
/// @dev Only the authenticated account can enable balance forwarding for itself
/// @dev Should call the IBalanceTracker hook with the current account's balance
function enableBalanceForwarder() external;
/// @notice Disables balance forwarding for the authenticated account
/// @dev Only the authenticated account can disable balance forwarding for itself
/// @dev Should call the IBalanceTracker hook with the account's balance of 0
function disableBalanceForwarder() external;
}
/// @title IGovernance
/// @notice Interface of the EVault's Governance module
interface IGovernance {
/// @notice Retrieves the address of the governor
/// @return The governor address
function governorAdmin() external view returns (address);
/// @notice Retrieves address of the governance fee receiver
/// @return The fee receiver address
function feeReceiver() external view returns (address);
/// @notice Retrieves the interest fee in effect for the vault
/// @return Amount of interest that is redirected as a fee, as a fraction scaled by 1e4
function interestFee() external view returns (uint16);
/// @notice Looks up an asset's currently configured interest rate model
/// @return Address of the interest rate contract or address zero to indicate 0% interest
function interestRateModel() external view returns (address);
/// @notice Retrieves the ProtocolConfig address
/// @return The protocol config address
function protocolConfigAddress() external view returns (address);
/// @notice Retrieves the protocol fee share
/// @return A percentage share of fees accrued belonging to the protocol, in 1e4 scale
function protocolFeeShare() external view returns (uint256);
/// @notice Retrieves the address which will receive protocol's fees
/// @notice The protocol fee receiver address
function protocolFeeReceiver() external view returns (address);
/// @notice Retrieves supply and borrow caps in AmountCap format
/// @return supplyCap The supply cap in AmountCap format
/// @return borrowCap The borrow cap in AmountCap format
function caps() external view returns (uint16 supplyCap, uint16 borrowCap);
/// @notice Retrieves the borrow LTV of the collateral, which is used to determine if the account is healthy during
/// account status checks.
/// @param collateral The address of the collateral to query
/// @return Borrowing LTV in 1e4 scale
function LTVBorrow(address collateral) external view returns (uint16);
/// @notice Retrieves the current liquidation LTV, which is used to determine if the account is eligible for
/// liquidation
/// @param collateral The address of the collateral to query
/// @return Liquidation LTV in 1e4 scale
function LTVLiquidation(address collateral) external view returns (uint16);
/// @notice Retrieves LTV configuration for the collateral
/// @param collateral Collateral asset
/// @return borrowLTV The current value of borrow LTV for originating positions
/// @return liquidationLTV The value of fully converged liquidation LTV
/// @return initialLiquidationLTV The initial value of the liquidation LTV, when the ramp began
/// @return targetTimestamp The timestamp when the liquidation LTV is considered fully converged
/// @return rampDuration The time it takes for the liquidation LTV to converge from the initial value to the fully
/// converged value
function LTVFull(address collateral)
external
view
returns (
uint16 borrowLTV,
uint16 liquidationLTV,
uint16 initialLiquidationLTV,
uint48 targetTimestamp,
uint32 rampDuration
);
/// @notice Retrieves a list of collaterals with configured LTVs
/// @return List of asset collaterals
/// @dev Returned assets could have the ltv disabled (set to zero)
function LTVList() external view returns (address[] memory);
/// @notice Retrieves the maximum liquidation discount
/// @return The maximum liquidation discount in 1e4 scale
/// @dev The default value, which is zero, is deliberately bad, as it means there would be no incentive to liquidate
/// unhealthy users. The vault creator must take care to properly select the limit, given the underlying and
/// collaterals used.
function maxLiquidationDiscount() external view returns (uint16);
/// @notice Retrieves liquidation cool-off time, which must elapse after successful account status check before
/// account can be liquidated
/// @return The liquidation cool off time in seconds
function liquidationCoolOffTime() external view returns (uint16);
/// @notice Retrieves a hook target and a bitmask indicating which operations call the hook target
/// @return hookTarget Address of the hook target contract
/// @return hookedOps Bitmask with operations that should call the hooks. See Constants.sol for a list of operations
function hookConfig() external view returns (address hookTarget, uint32 hookedOps);
/// @notice Retrieves a bitmask indicating enabled config flags
/// @return Bitmask with config flags enabled
function configFlags() external view returns (uint32);
/// @notice Address of EthereumVaultConnector contract
/// @return The EVC address
function EVC() external view returns (address);
/// @notice Retrieves a reference asset used for liquidity calculations
/// @return The address of the reference asset
function unitOfAccount() external view returns (address);
/// @notice Retrieves the address of the oracle contract
/// @return The address of the oracle
function oracle() external view returns (address);
/// @notice Retrieves the Permit2 contract address
/// @return The address of the Permit2 contract
function permit2Address() external view returns (address);
/// @notice Splits accrued fees balance according to protocol fee share and transfers shares to the governor fee
/// receiver and protocol fee receiver
function convertFees() external;
/// @notice Set a new governor address
/// @param newGovernorAdmin The new governor address
/// @dev Set to zero address to renounce privileges and make the vault non-governed
function setGovernorAdmin(address newGovernorAdmin) external;
/// @notice Set a new governor fee receiver address
/// @param newFeeReceiver The new fee receiver address
function setFeeReceiver(address newFeeReceiver) external;
/// @notice Set a new LTV config
/// @param collateral Address of collateral to set LTV for
/// @param borrowLTV New borrow LTV, for assessing account's health during account status checks, in 1e4 scale
/// @param liquidationLTV New liquidation LTV after ramp ends in 1e4 scale
/// @param rampDuration Ramp duration in seconds
function setLTV(address collateral, uint16 borrowLTV, uint16 liquidationLTV, uint32 rampDuration) external;
/// @notice Set a new maximum liquidation discount
/// @param newDiscount New maximum liquidation discount in 1e4 scale
/// @dev If the discount is zero (the default), the liquidators will not be incentivized to liquidate unhealthy
/// accounts
function setMaxLiquidationDiscount(uint16 newDiscount) external;
/// @notice Set a new liquidation cool off time, which must elapse after successful account status check before
/// account can be liquidated
/// @param newCoolOffTime The new liquidation cool off time in seconds
/// @dev Setting cool off time to zero allows liquidating the account in the same block as the last successful
/// account status check
function setLiquidationCoolOffTime(uint16 newCoolOffTime) external;
/// @notice Set a new interest rate model contract
/// @param newModel The new IRM address
/// @dev If the new model reverts, perhaps due to governor error, the vault will silently use a zero interest
/// rate. Governor should make sure the new interest rates are computed as expected.
function setInterestRateModel(address newModel) external;
/// @notice Set a new hook target and a new bitmap indicating which operations should call the hook target.
/// Operations are defined in Constants.sol.
/// @param newHookTarget The new hook target address. Use address(0) to simply disable hooked operations
/// @param newHookedOps Bitmask with the new hooked operations
/// @dev All operations are initially disabled in a newly created vault. The vault creator must set their
/// own configuration to make the vault usable
function setHookConfig(address newHookTarget, uint32 newHookedOps) external;
/// @notice Set new bitmap indicating which config flags should be enabled. Flags are defined in Constants.sol
/// @param newConfigFlags Bitmask with the new config flags
function setConfigFlags(uint32 newConfigFlags) external;
/// @notice Set new supply and borrow caps in AmountCap format
/// @param supplyCap The new supply cap in AmountCap fromat
/// @param borrowCap The new borrow cap in AmountCap fromat
function setCaps(uint16 supplyCap, uint16 borrowCap) external;
/// @notice Set a new interest fee
/// @param newFee The new interest fee
function setInterestFee(uint16 newFee) external;
}
/// @title IEVault
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Interface of the EVault, an EVC enabled lending vault
interface IEVault is
IInitialize,
IToken,
IVault,
IBorrowing,
ILiquidation,
IRiskManager,
IBalanceForwarder,
IGovernance
{
/// @notice Fetch address of the `Initialize` module
function MODULE_INITIALIZE() external view returns (address);
/// @notice Fetch address of the `Token` module
function MODULE_TOKEN() external view returns (address);
/// @notice Fetch address of the `Vault` module
function MODULE_VAULT() external view returns (address);
/// @notice Fetch address of the `Borrowing` module
function MODULE_BORROWING() external view returns (address);
/// @notice Fetch address of the `Liquidation` module
function MODULE_LIQUIDATION() external view returns (address);
/// @notice Fetch address of the `RiskManager` module
function MODULE_RISKMANAGER() external view returns (address);
/// @notice Fetch address of the `BalanceForwarder` module
function MODULE_BALANCE_FORWARDER() external view returns (address);
/// @notice Fetch address of the `Governance` module
function MODULE_GOVERNANCE() external view returns (address);
}
lib/euler-vault-kit/src/EVault/shared/Errors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Errors
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Contract implementing EVault's custom errors
contract Errors {
error E_Initialized();
error E_ProxyMetadata();
error E_SelfTransfer();
error E_InsufficientAllowance();
error E_InsufficientCash();
error E_InsufficientAssets();
error E_InsufficientBalance();
error E_InsufficientDebt();
error E_FlashLoanNotRepaid();
error E_Reentrancy();
error E_OperationDisabled();
error E_OutstandingDebt();
error E_AmountTooLargeToEncode();
error E_DebtAmountTooLargeToEncode();
error E_RepayTooMuch();
error E_TransientState();
error E_SelfLiquidation();
error E_ControllerDisabled();
error E_CollateralDisabled();
error E_ViolatorLiquidityDeferred();
error E_LiquidationCoolOff();
error E_ExcessiveRepayAmount();
error E_MinYield();
error E_BadAddress();
error E_ZeroAssets();
error E_ZeroShares();
error E_Unauthorized();
error E_CheckUnauthorized();
error E_NotSupported();
error E_EmptyError();
error E_BadBorrowCap();
error E_BadSupplyCap();
error E_BadCollateral();
error E_AccountLiquidity();
error E_NoLiability();
error E_NotController();
error E_BadFee();
error E_SupplyCapExceeded();
error E_BorrowCapExceeded();
error E_InvalidLTVAsset();
error E_NoPriceOracle();
error E_ConfigAmountTooLargeToEncode();
error E_BadAssetReceiver();
error E_BadSharesOwner();
error E_BadSharesReceiver();
error E_BadMaxLiquidationDiscount();
error E_LTVBorrow();
error E_LTVLiquidation();
error E_NotHookTarget();
}
lib/euler-vault-kit/src/EVault/shared/lib/RPow.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @custom:security-contact [email protected]
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
/// @author Modified by Euler Labs (https://www.eulerlabs.com/) to return an `overflow` bool instead of reverting
library RPow {
/// @dev If overflow is true, an overflow occurred and the value of z is undefined
function rpow(uint256 x, uint256 n, uint256 scalar) internal pure returns (uint256 z, bool overflow) {
/// @solidity memory-safe-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Bail if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
overflow := 1
break
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Bail if xx + half overflowed.
if lt(xxRound, xx) {
overflow := 1
break
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Bail if x is non-zero.
if iszero(iszero(x)) {
overflow := 1
break
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Bail if zx + half overflowed.
if lt(zxRound, zx) {
overflow := 1
break
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
}
lib/reward-streams/src/interfaces/IBalanceTracker.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title IBalanceTracker
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Provides an interface for tracking the balance of accounts.
interface IBalanceTracker {
/// @notice Executes the balance tracking hook for an account.
/// @dev This function must be called with the current balance of the account when enabling the balance forwarding
/// for it. This function must be called with 0 balance of the account when disabling the balance forwarding for it.
/// This function allows to be called on zero balance transfers, when the newAccountBalance is the same as the
/// previous one. To prevent DOS attacks, forfeitRecentReward should be used appropriately.
/// @param account The account address to execute the hook for.
/// @param newAccountBalance The new balance of the account.
/// @param forfeitRecentReward Whether to forfeit the most recent reward and not update the accumulator.
function balanceTrackerHook(address account, uint256 newAccountBalance, bool forfeitRecentReward) external;
}
lib/reward-streams/src/interfaces/IRewardStreams.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import "./IBalanceTracker.sol";
/// @title IRewardStreams
/// @custom:security-contact [email protected]
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Interface for Reward Streams distributor contract.
interface IRewardStreams {
function EPOCH_DURATION() external view returns (uint256);
function MAX_EPOCHS_AHEAD() external view returns (uint256);
function MAX_DISTRIBUTION_LENGTH() external view returns (uint256);
function MAX_REWARDS_ENABLED() external view returns (uint256);
function registerReward(address rewarded, address reward, uint48 startEpoch, uint128[] calldata rewardAmounts) external;
function updateReward(address rewarded, address reward, address recipient) external returns (uint256);
function claimReward(address rewarded, address reward, address recipient, bool ignoreRecentReward) external returns (uint256);
function enableReward(address rewarded, address reward) external returns (bool);
function disableReward(address rewarded, address reward, bool forfeitRecentReward) external returns (bool);
function earnedReward(address account, address rewarded, address reward, bool ignoreRecentReward) external view returns (uint256);
function enabledRewards(address account, address rewarded) external view returns (address[] memory);
function isRewardEnabled(address account, address rewarded, address reward) external view returns (bool);
function balanceOf(address account, address rewarded) external view returns (uint256);
function rewardAmount(address rewarded, address reward) external view returns (uint256);
function totalRewardedEligible(address rewarded, address reward) external view returns (uint256);
function totalRewardRegistered(address rewarded, address reward) external view returns (uint256);
function totalRewardClaimed(address rewarded, address reward) external view returns (uint256);
function rewardAmount(address rewarded, address reward, uint48 epoch) external view returns (uint256);
function currentEpoch() external view returns (uint48);
function getEpoch(uint48 timestamp) external view returns (uint48);
function getEpochStartTimestamp(uint48 epoch) external view returns (uint48);
function getEpochEndTimestamp(uint48 epoch) external view returns (uint48);
}
/// @title ITrackingRewardStreams
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Interface for Tracking Reward Streams. Extends `IRewardStreams` and `IBalanceTracker`.
interface ITrackingRewardStreams is IRewardStreams, IBalanceTracker {}
/// @title IStakingRewardStreams
/// @author Euler Labs (https://www.eulerlabs.com/)
/// @notice Interface for Staking Reward Streams. Extends `IRewardStreams` with staking functionality.
interface IStakingRewardStreams is IRewardStreams {
function stake(address rewarded, uint256 amount) external;
function unstake(address rewarded, uint256 amount, address recipient, bool forfeitRecentReward) external;
}
src/Lens/LensTypes.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
struct AccountInfo {
EVCAccountInfo evcAccountInfo;
VaultAccountInfo vaultAccountInfo;
AccountRewardInfo accountRewardInfo;
}
struct AccountMultipleVaultsInfo {
EVCAccountInfo evcAccountInfo;
VaultAccountInfo[] vaultAccountInfo;
AccountRewardInfo[] accountRewardInfo;
}
struct EVCAccountInfo {
uint256 timestamp;
address evc;
address account;
bytes19 addressPrefix;
address owner;
bool isLockdownMode;
bool isPermitDisabledMode;
uint256 lastAccountStatusCheckTimestamp;
address[] enabledControllers;
address[] enabledCollaterals;
}
struct VaultAccountInfo {
bool queryFailure;
bytes queryFailureReason;
uint256 timestamp;
address account;
address vault;
address asset;
uint256 assetsAccount;
uint256 shares;
uint256 assets;
uint256 borrowed;
uint256 assetAllowanceVault;
uint256 assetAllowanceVaultPermit2;
uint256 assetAllowanceExpirationVaultPermit2;
uint256 assetAllowancePermit2;
bool balanceForwarderEnabled;
bool isController;
bool isCollateral;
AccountLiquidityInfo liquidityInfo;
}
struct AccountLiquidityInfo {
bool queryFailure;
bytes queryFailureReason;
address account;
address vault;
address unitOfAccount;
int256 timeToLiquidation;
uint256 liabilityValueBorrowing;
uint256 liabilityValueLiquidation;
uint256 collateralValueBorrowing;
uint256 collateralValueLiquidation;
uint256 collateralValueRaw;
address[] collaterals;
uint256[] collateralValuesBorrowing;
uint256[] collateralValuesLiquidation;
uint256[] collateralValuesRaw;
}
struct VaultInfoERC4626 {
uint256 timestamp;
address vault;
string vaultName;
string vaultSymbol;
uint256 vaultDecimals;
address asset;
string assetName;
string assetSymbol;
uint256 assetDecimals;
uint256 totalShares;
uint256 totalAssets;
bool isEVault;
}
struct VaultInfoStatic {
uint256 timestamp;
address vault;
string vaultName;
string vaultSymbol;
uint256 vaultDecimals;
address asset;
string assetName;
string assetSymbol;
uint256 assetDecimals;
address unitOfAccount;
string unitOfAccountName;
string unitOfAccountSymbol;
uint256 unitOfAccountDecimals;
address dToken;
address oracle;
address evc;
address protocolConfig;
address balanceTracker;
address permit2;
address creator;
}
struct VaultInfoDynamic {
uint256 timestamp;
address vault;
uint256 totalShares;
uint256 totalCash;
uint256 totalBorrowed;
uint256 totalAssets;
uint256 accumulatedFeesShares;
uint256 accumulatedFeesAssets;
address governorFeeReceiver;
address protocolFeeReceiver;
uint256 protocolFeeShare;
uint256 interestFee;
uint256 hookedOperations;
uint256 configFlags;
uint256 supplyCap;
uint256 borrowCap;
uint256 maxLiquidationDiscount;
uint256 liquidationCoolOffTime;
address interestRateModel;
address hookTarget;
address governorAdmin;
VaultInterestRateModelInfo irmInfo;
LTVInfo[] collateralLTVInfo;
AssetPriceInfo liabilityPriceInfo;
AssetPriceInfo[] collateralPriceInfo;
OracleDetailedInfo oracleInfo;
AssetPriceInfo backupAssetPriceInfo;
OracleDetailedInfo backupAssetOracleInfo;
}
struct VaultInfoFull {
uint256 timestamp;
address vault;
string vaultName;
string vaultSymbol;
uint256 vaultDecimals;
address asset;
string assetName;
string assetSymbol;
uint256 assetDecimals;
address unitOfAccount;
string unitOfAccountName;
string unitOfAccountSymbol;
uint256 unitOfAccountDecimals;
uint256 totalShares;
uint256 totalCash;
uint256 totalBorrowed;
uint256 totalAssets;
uint256 accumulatedFeesShares;
uint256 accumulatedFeesAssets;
address governorFeeReceiver;
address protocolFeeReceiver;
uint256 protocolFeeShare;
uint256 interestFee;
uint256 hookedOperations;
uint256 configFlags;
uint256 supplyCap;
uint256 borrowCap;
uint256 maxLiquidationDiscount;
uint256 liquidationCoolOffTime;
address dToken;
address oracle;
address interestRateModel;
address hookTarget;
address evc;
address protocolConfig;
address balanceTracker;
address permit2;
address creator;
address governorAdmin;
VaultInterestRateModelInfo irmInfo;
LTVInfo[] collateralLTVInfo;
AssetPriceInfo liabilityPriceInfo;
AssetPriceInfo[] collateralPriceInfo;
OracleDetailedInfo oracleInfo;
AssetPriceInfo backupAssetPriceInfo;
OracleDetailedInfo backupAssetOracleInfo;
}
struct LTVInfo {
address collateral;
uint256 borrowLTV;
uint256 liquidationLTV;
uint256 initialLiquidationLTV;
uint256 targetTimestamp;
uint256 rampDuration;
}
struct AssetPriceInfo {
bool queryFailure;
bytes queryFailureReason;
uint256 timestamp;
address oracle;
address asset;
address unitOfAccount;
uint256 amountIn;
uint256 amountOutMid;
uint256 amountOutBid;
uint256 amountOutAsk;
}
struct VaultInterestRateModelInfo {
bool queryFailure;
bytes queryFailureReason;
address vault;
address interestRateModel;
InterestRateInfo[] interestRateInfo;
InterestRateModelDetailedInfo interestRateModelInfo;
}
struct InterestRateInfo {
uint256 cash;
uint256 borrows;
uint256 borrowSPY;
uint256 borrowAPY;
uint256 supplyAPY;
}
enum InterestRateModelType {
UNKNOWN,
KINK,
ADAPTIVE_CURVE,
KINKY,
FIXED_CYCLICAL_BINARY,
FIXED_CYCLICAL_BINARY_MONTHLY
}
struct InterestRateModelDetailedInfo {
address interestRateModel;
InterestRateModelType interestRateModelType;
bytes interestRateModelParams;
}
struct KinkIRMInfo {
uint256 baseRate;
uint256 slope1;
uint256 slope2;
uint256 kink;
}
struct AdaptiveCurveIRMInfo {
int256 targetUtilization;
int256 initialRateAtTarget;
int256 minRateAtTarget;
int256 maxRateAtTarget;
int256 curveSteepness;
int256 adjustmentSpeed;
}
struct KinkyIRMInfo {
uint256 baseRate;
uint256 slope;
uint256 shape;
uint256 kink;
uint256 cutoff;
}
struct FixedCyclicalBinaryIRMInfo {
uint256 primaryRate;
uint256 secondaryRate;
uint256 primaryDuration;
uint256 secondaryDuration;
uint256 startTimestamp;
}
struct FixedCyclicalBinaryMonthlyIRMInfo {
uint256 primaryRate;
uint256 secondaryRate;
uint256 cycleStartDay;
uint256 secondaryDays;
}
struct AccountRewardInfo {
uint256 timestamp;
address account;
address vault;
address balanceTracker;
bool balanceForwarderEnabled;
uint256 balance;
EnabledRewardInfo[] enabledRewardsInfo;
}
struct EnabledRewardInfo {
address reward;
uint256 earnedReward;
uint256 earnedRewardRecentIgnored;
}
struct VaultRewardInfo {
uint256 timestamp;
address vault;
address reward;
string rewardName;
string rewardSymbol;
uint8 rewardDecimals;
address balanceTracker;
uint256 epochDuration;
uint256 currentEpoch;
uint256 totalRewardedEligible;
uint256 totalRewardRegistered;
uint256 totalRewardClaimed;
RewardAmountInfo[] epochInfoPrevious;
RewardAmountInfo[] epochInfoUpcoming;
}
struct RewardAmountInfo {
uint256 epoch;
uint256 epochStart;
uint256 epochEnd;
uint256 rewardAmount;
}
struct OracleDetailedInfo {
address oracle;
string name;
bytes oracleInfo;
}
struct EulerRouterInfo {
address governor;
address fallbackOracle;
OracleDetailedInfo fallbackOracleInfo;
address[] bases;
address[] quotes;
address[][] resolvedAssets;
address[] resolvedOracles;
OracleDetailedInfo[] resolvedOraclesInfo;
}
struct ChainlinkOracleInfo {
address base;
address quote;
address feed;
string feedDescription;
uint256 maxStaleness;
}
struct ChainlinkInfrequentOracleInfo {
address base;
address quote;
address feed;
string feedDescription;
uint256 maxStaleness;
}
struct ChronicleOracleInfo {
address base;
address quote;
address feed;
uint256 maxStaleness;
}
struct LidoOracleInfo {
address base;
address quote;
}
struct LidoFundamentalOracleInfo {
address base;
address quote;
}
struct PythOracleInfo {
address pyth;
address base;
address quote;
bytes32 feedId;
uint256 maxStaleness;
uint256 maxConfWidth;
}
struct RedstoneCoreOracleInfo {
address base;
address quote;
bytes32 feedId;
uint8 feedDecimals;
uint256 maxStaleness;
uint208 cachePrice;
uint48 cachePriceTimestamp;
}
struct UniswapV3OracleInfo {
address tokenA;
address tokenB;
address pool;
uint24 fee;
uint32 twapWindow;
}
struct FixedRateOracleInfo {
address base;
address quote;
uint256 rate;
}
struct RateProviderOracleInfo {
address base;
address quote;
address rateProvider;
}
struct OndoOracleInfo {
address base;
address quote;
address rwaOracle;
}
struct PendleProviderOracleInfo {
address base;
address quote;
address pendleMarket;
uint32 twapWindow;
}
struct PendleUniversalOracleInfo {
address base;
address quote;
address pendleMarket;
uint32 twapWindow;
}
struct CurveEMAOracleInfo {
address base;
address quote;
address pool;
uint256 priceOracleIndex;
}
struct SwaapSafeguardProviderOracleInfo {
address base;
address quote;
bytes32 poolId;
}
struct CrossAdapterInfo {
address base;
address cross;
address quote;
address oracleBaseCross;
address oracleCrossQuote;
OracleDetailedInfo oracleBaseCrossInfo;
OracleDetailedInfo oracleCrossQuoteInfo;
}
struct EulerEarnVaultInfoFull {
uint256 timestamp;
address vault;
string vaultName;
string vaultSymbol;
uint256 vaultDecimals;
address asset;
string assetName;
string assetSymbol;
uint256 assetDecimals;
uint256 totalShares;
uint256 totalAssets;
uint256 lostAssets;
uint256 availableAssets;
uint256 timelock;
uint256 performanceFee;
address feeReceiver;
address owner;
address creator;
address curator;
address guardian;
address evc;
address permit2;
uint256 pendingTimelock;
uint256 pendingTimelockValidAt;
address pendingGuardian;
uint256 pendingGuardianValidAt;
address[] supplyQueue;
EulerEarnVaultStrategyInfo[] strategies;
}
struct EulerEarnVaultStrategyInfo {
address strategy;
uint256 allocatedAssets;
uint256 availableAssets;
uint256 currentAllocationCap;
uint256 pendingAllocationCap;
uint256 pendingAllocationCapValidAt;
uint256 removableAt;
VaultInfoERC4626 info;
}
src/Lens/Utils.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IEVault} from "evk/EVault/IEVault.sol";
import {RPow} from "evk/EVault/shared/lib/RPow.sol";
abstract contract Utils {
uint256 internal constant SECONDS_PER_YEAR = 365.2425 * 86400;
uint256 internal constant ONE = 1e27;
uint256 internal constant CONFIG_SCALE = 1e4;
uint256 internal constant TTL_HS_ACCURACY = ONE / 1e4;
int256 internal constant TTL_COMPUTATION_MIN = 0;
int256 internal constant TTL_COMPUTATION_MAX = 400 * 1 days;
int256 public constant TTL_INFINITY = type(int256).max;
int256 public constant TTL_MORE_THAN_ONE_YEAR = type(int256).max - 1;
int256 public constant TTL_LIQUIDATION = -1;
int256 public constant TTL_ERROR = -2;
function getWETHAddress() internal view returns (address) {
if (block.chainid == 1) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
} else if (
block.chainid == 10 || block.chainid == 130 || block.chainid == 8453 || block.chainid == 1923
|| block.chainid == 480 || block.chainid == 57073 || block.chainid == 60808
) {
return 0x4200000000000000000000000000000000000006;
} else if (block.chainid == 56) {
return 0x2170Ed0880ac9A755fd29B2688956BD959F933F8;
} else if (block.chainid == 100) {
return 0x6A023CCd1ff6F2045C3309768eAd9E68F978f6e1;
} else if (block.chainid == 137) {
return 0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619;
} else if (block.chainid == 146) {
return 0x50c42dEAcD8Fc9773493ED674b675bE577f2634b;
} else if (block.chainid == 42161) {
return 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1;
} else if (block.chainid == 43114) {
return 0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB;
} else if (block.chainid == 747474) {
return 0xEE7D8BCFb72bC1880D0Cf19822eB0A2e6577aB62;
} else if (block.chainid == 80094) {
return 0x2F6F07CDcf3588944Bf4C42aC74ff24bF56e7590;
} else {
// bitcoin-specific and test networks
if (
block.chainid == 30 || block.chainid == 21000000 || block.chainid == 10143 || block.chainid == 80084
|| block.chainid == 2390 || block.chainid == 998
) {
return address(0);
}
// hyperEVM
if (block.chainid == 999) {
return address(0);
}
// TAC
if (block.chainid == 239) {
return address(0);
}
// Plasma
if (block.chainid == 9745) {
return address(0);
}
// Monad
if (block.chainid == 143) {
return address(0);
}
// Hashkey
if (block.chainid == 177) {
return address(0);
}
// Sepolia
if (block.chainid == 11155111) {
return address(0);
}
}
revert("getWETHAddress: Unsupported chain");
}
function _strEq(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
/// @dev External so it can be wrapped in try/catch. Decoding a dynamic type validates offsets and lengths and
/// reverts on malformed data, which cannot be checked up front the way a single word can.
function decodeString(bytes memory data) external pure returns (string memory) {
return abi.decode(data, (string));
}
/// @dev abi.decode(data, (address)) reverts when the high-order 96 bits are dirty. Decoding a word as uint256
/// never reverts, so the range can be checked instead.
function _tryDecodeAddress(bytes memory data) internal pure returns (bool ok, address value) {
if (data.length < 32) return (false, address(0));
uint256 word = abi.decode(data, (uint256));
if (word > type(uint160).max) return (false, address(0));
return (true, address(uint160(word)));
}
/// @dev abi.decode(data, (uint8)) reverts when the high-order bits are dirty.
function _tryDecodeUint8(bytes memory data) internal pure returns (bool ok, uint8 value) {
if (data.length < 32) return (false, 0);
uint256 word = abi.decode(data, (uint256));
if (word > type(uint8).max) return (false, 0);
return (true, uint8(word));
}
/// @dev See decodeString for why this cannot be done inline.
function _tryDecodeString(bytes memory data) internal view returns (bool ok, string memory value) {
try this.decodeString(data) returns (string memory decoded) {
return (true, decoded);
} catch {
return (false, "");
}
}
/// @dev for tokens like MKR which return bytes32 on name() or symbol()
function _getStringOrBytes32(address contractAddress, bytes4 selector) internal view returns (string memory) {
(bool success, bytes memory result) = contractAddress.staticcall(abi.encodeWithSelector(selector));
if (!success || result.length == 0) return "";
if (result.length == 32) return string(abi.encodePacked(result));
(, string memory decoded) = _tryDecodeString(result);
return decoded;
}
function _getDecimals(address contractAddress) internal view returns (uint8) {
(bool success, bytes memory data) =
contractAddress.staticcall(abi.encodeCall(IEVault(contractAddress).decimals, ()));
if (!success) return 18;
(bool ok, uint8 decimals) = _tryDecodeUint8(data);
return ok ? decimals : 18;
}
function _computeAPYs(uint256 borrowSPY, uint256 cash, uint256 borrows, uint256 interestFee)
internal
pure
returns (uint256 borrowAPY, uint256 supplyAPY)
{
uint256 totalAssets = cash + borrows;
bool overflow;
(borrowAPY, overflow) = RPow.rpow(borrowSPY + ONE, SECONDS_PER_YEAR, ONE);
if (overflow) return (0, 0);
borrowAPY -= ONE;
supplyAPY =
totalAssets == 0 ? 0 : borrowAPY * borrows * (CONFIG_SCALE - interestFee) / totalAssets / CONFIG_SCALE;
}
struct CollateralInfo {
uint256 borrowSPY;
uint256 borrows;
uint256 totalAssets;
uint256 interestFee;
uint256 borrowInterest;
}
function _calculateTimeToLiquidation(
address liabilityVault,
uint256 liabilityValue,
address[] memory collaterals,
uint256[] memory collateralValues
) internal view returns (int256) {
// if there's no liability, time to liquidation is infinite
if (liabilityValue == 0) return TTL_INFINITY;
// get borrow interest rate
uint256 liabilitySPY;
{
(bool success, bytes memory data) =
liabilityVault.staticcall(abi.encodeCall(IEVault(liabilityVault).interestRate, ()));
if (success && data.length >= 32) {
liabilitySPY = abi.decode(data, (uint256));
}
}
// get individual collateral interest rates and total collateral value
CollateralInfo[] memory collateralInfos = new CollateralInfo[](collaterals.length);
uint256 collateralValue;
for (uint256 i = 0; i < collaterals.length; ++i) {
address collateral = collaterals[i];
(bool success, bytes memory data) =
collateral.staticcall(abi.encodeCall(IEVault(collateral).interestRate, ()));
if (success && data.length >= 32) {
collateralInfos[i].borrowSPY = abi.decode(data, (uint256));
}
(success, data) = collateral.staticcall(abi.encodeCall(IEVault(collateral).totalBorrows, ()));
if (success && data.length >= 32) {
collateralInfos[i].borrows = abi.decode(data, (uint256));
}
(success, data) = collateral.staticcall(abi.encodeCall(IEVault(collateral).cash, ()));
if (success && data.length >= 32) {
collateralInfos[i].totalAssets = abi.decode(data, (uint256)) + collateralInfos[i].borrows;
}
(success, data) = collateral.staticcall(abi.encodeCall(IEVault(collateral).interestFee, ()));
if (success && data.length >= 32) {
collateralInfos[i].interestFee = abi.decode(data, (uint256));
}
collateralValue += collateralValues[i];
}
// if liability is greater than or equal to collateral, the account is eligible for liquidation right away
if (liabilityValue >= collateralValue) return TTL_LIQUIDATION;
// if there's no borrow interest rate, time to liquidation is infinite
if (liabilitySPY == 0) return TTL_INFINITY;
int256 minTTL = TTL_COMPUTATION_MIN;
int256 maxTTL = TTL_COMPUTATION_MAX;
int256 ttl;
// calculate time to liquidation using binary search
while (true) {
ttl = minTTL + (maxTTL - minTTL) / 2;
// break if the search range is too small
if (maxTTL <= minTTL + 1 days) break;
if (ttl < 1 days) break;
// calculate the liability interest accrued
uint256 liabilityInterest;
if (liabilitySPY > 0) {
(uint256 multiplier, bool overflow) = RPow.rpow(liabilitySPY + ONE, uint256(ttl), ONE);
if (overflow) return TTL_ERROR;
liabilityInterest = liabilityValue * multiplier / ONE - liabilityValue;
}
// calculate the collaterals interest accrued
uint256 collateralInterest;
for (uint256 i = 0; i < collaterals.length; ++i) {
if (collateralInfos[i].borrowSPY == 0 || collateralInfos[i].totalAssets == 0) continue;
(uint256 multiplier, bool overflow) = RPow.rpow(collateralInfos[i].borrowSPY + ONE, uint256(ttl), ONE);
if (overflow) return TTL_ERROR;
collateralInfos[i].borrowInterest = collateralValues[i] * multiplier / ONE - collateralValues[i];
collateralInterest += collateralInfos[i].borrowInterest * collateralInfos[i].borrows
* (CONFIG_SCALE - collateralInfos[i].interestFee) / collateralInfos[i].totalAssets / CONFIG_SCALE;
}
// calculate the health factor
uint256 hs = (collateralValue + collateralInterest) * ONE / (liabilityValue + liabilityInterest);
// if the collateral interest accrues fater than the liability interest, the account should never be
// liquidated
if (collateralInterest >= liabilityInterest) return TTL_INFINITY;
// if the health factor is within the acceptable range, return the time to liquidation
if (hs >= ONE && hs - ONE <= TTL_HS_ACCURACY) break;
if (hs < ONE && ONE - hs <= TTL_HS_ACCURACY) break;
// adjust the search range
if (hs >= ONE) minTTL = ttl + 1 days;
else maxTTL = ttl - 1 days;
}
return ttl > int256(SECONDS_PER_YEAR) ? TTL_MORE_THAN_ONE_YEAR : int256(ttl) / 1 days;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 20000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"lib/euler-price-oracle:@openzeppelin/contracts/=lib/euler-price-oracle/lib/openzeppelin-contracts/contracts/",
"lib/euler-earn:@openzeppelin/=lib/euler-earn/lib/openzeppelin-contracts/",
"lib/euler-earn:@openzeppelin-upgradeable/=lib/euler-earn/lib/openzeppelin-contracts-upgradeable/contracts/",
"lib/euler-earn:ethereum-vault-connector/=lib/euler-earn/lib/ethereum-vault-connector/src/",
"lib/layerzero-devtools/packages/oft-evm/contracts:@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts/contracts/",
"lib/layerzero-devtools/packages/oft-evm-upgradeable/contracts:@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"lib/layerzero-devtools/packages/oapp-evm-upgradeable/contracts:@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@layerzerolabs/oft-evm/=lib/layerzero-devtools/packages/oft-evm/",
"@layerzerolabs/oapp-evm/=lib/layerzero-devtools/packages/oapp-evm/",
"@layerzerolabs/oapp-evm-upgradeable/=lib/layerzero-devtools/packages/oapp-evm-upgradeable/",
"@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/protocol/",
"@layerzerolabs/lz-evm-messagelib-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/messagelib/",
"@layerzerolabs/lz-evm-oapp-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/oapp/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"lib/fee-flow/src:solmate/=lib/fee-flow/lib/solmate/src/",
"lib/fee-flow/utils:solmate/=lib/fee-flow/lib/solmate/utils/",
"lib/fee-flow/tokens:solmate/=lib/fee-flow/lib/solmate/tokens/",
"lib/euler-swap:solmate/=lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/src/",
"ethereum-vault-connector/=lib/ethereum-vault-connector/src/",
"evc/=lib/ethereum-vault-connector/src/",
"evk/=lib/euler-vault-kit/src/",
"evk-test/=lib/euler-vault-kit/test/",
"euler-price-oracle/=lib/euler-price-oracle/src/",
"euler-price-oracle-test/=lib/euler-price-oracle/test/",
"fee-flow/=lib/fee-flow/src/",
"reward-streams/=lib/reward-streams/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"euler-earn/=lib/euler-earn/src/",
"layerzero/oft-evm/=lib/layerzero-devtools/packages/oft-evm/contracts/",
"layerzero/oft-evm-upgradeable/=lib/layerzero-devtools/packages/oft-evm-upgradeable/contracts/",
"solidity-bytes-utils/=lib/solidity-bytes-utils/",
"@ensdomains/=lib/euler-swap/lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@pendle/core-v2/=lib/euler-price-oracle/lib/pendle-core-v2-public/contracts/",
"@pyth/=lib/euler-price-oracle/lib/pyth-sdk-solidity/",
"@redstone/evm-connector/=lib/euler-price-oracle/lib/redstone-oracles-monorepo/packages/evm-connector/contracts/",
"@solady/=lib/euler-price-oracle/lib/solady/src/",
"@uniswap/v3-core/=lib/euler-price-oracle/lib/v3-core/",
"@uniswap/v3-periphery/=lib/euler-price-oracle/lib/v3-periphery/",
"@uniswap/v4-core/=lib/euler-swap/lib/v4-periphery/lib/v4-core/",
"ds-test/=lib/ethereum-vault-connector/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"euler-swap/=lib/euler-swap/",
"euler-vault-kit/=lib/euler-vault-kit/",
"forge-gas-snapshot/=lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/euler-swap/lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
"layerzero-devtools/=lib/layerzero-devtools/packages/toolbox-foundry/src/",
"layerzero-v2/=lib/layerzero-v2/",
"openzeppelin/=lib/ethereum-vault-connector/lib/openzeppelin-contracts/contracts/",
"pendle-core-v2-public/=lib/euler-price-oracle/lib/pendle-core-v2-public/contracts/",
"permit2/=lib/euler-vault-kit/lib/permit2/",
"pyth-sdk-solidity/=lib/euler-price-oracle/lib/pyth-sdk-solidity/",
"redstone-oracles-monorepo/=lib/euler-price-oracle/lib/",
"solady/=lib/euler-price-oracle/lib/solady/src/",
"solmate/=lib/fee-flow/lib/solmate/src/",
"v3-core/=lib/euler-price-oracle/lib/v3-core/contracts/",
"v3-periphery/=lib/euler-price-oracle/lib/v3-periphery/contracts/",
"v4-core/=lib/euler-swap/lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/euler-swap/lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.