Yearn Lens

Yearn Lens

Architecture

Block Diagram

Key Concepts

Key Features

Contracts

Registry Adapters

Schema

Standardized Interfaces

AdapterMetadata

Asset

AssetStatic (static) (not connected)

Token (static) (not connected)

AssetDynamic (dynamic) (not connected)

TokenAmount (dynamic)

Position (dynamic) (connected)

Position

Token

TokenPosition

Adapter-specific Interfaces

Vault

Earn

Iron Bank

veCrv

Methods

registryAddress

assetsLength

Solidity

Example Response

positionSpenderAddresses

setPositionSpenderAddresses

assetsAddresses

Solidity

Example Response

assetTvl

Solidity

Example Response

assetsTvl

Solidity

Example Response

asset

Solidity

Example Response

assets

Solidity

Example Response

positionOf

Solidity

Example Response

positionsOf

Solidity

Example Response

tokens

Solidity

Example Response

Oracle

Methods

setCalculations

calculations

Example Response

getPriceUsdcRecommended

Example Response

getNormalizedValueUsdc

Example Response

tokenAliases

addTokenAlias

addTokenAliases

removeTokenAlias

Calculation

Standardized methods

getPriceUsdc

Example Response

Calculation specific methods

Sushiswap

Curve

IronBank

Lens

Methods

addAdapter

Solidity

removeAdapter

Solidity

adapters

Solidity

Example Response

assetsFromAdapter

assets

positionsFromAdapter

positionsOf

assetsLength

assetsAddresses

allowances

# Yearn Lens

Yearn Lens is a series of smart contracts that aggregate and format Yearn family protocol data into standardized interfaces.

## Architecture

### Block Diagram

![Chart](https://i.imgur.com/IWSIiJi.png)

### Key Concepts

- Lens

- The lens contract acts as the primary data aggregator

- Registry adapters can be added or removed from the lens contract

- The lens contract supports many of the same methods as the registry adapters, but returns aggregated views across asset types

- Registry Adapters

- The purpose of registry adapters is to read data from various registries and return data in a standardized format

- Currently registry adapters exist for:

- v1 Vaults

- v2 Vaults

- Earn

- Iron Bank

- veCrv

- All registry adapters must implement a standardized set of methods (details below)

- Registry adapters have the ability to return metadata specific to an asset type (for example for vaults: `pricePerShare`, `controller`, etc.)

- Oracle

- The oracle contract is responsible for fetching price information from various sources

- The oracle is intended for non-critical off-chain calculations

- TVL calculations

- Token and asset balance normalizations

- Not intended to be used with strategies or other contracts

- Prices are returned in USDC

- Supports adding, removing and upgrading price calculations

- Currently supported calculations:

- Sushiswap market price (based on `getAmountsOut`)

- Uniswap market price (based on `getAmountsOut`)

- Sushiswap/Uniswap LP token prices (based on `getReserves`)

- Iron Bank market price (based on `exchangeRateStored`)

- Curve LP token price (based on `virtualPrice` and base underlying token price)

- The oracle contract itself is very lightweight

- A cascading fallback mechanism is utilized to fetch the most appropriate price for a given asset

- This means the majority of logic lives on calculation contracts

- This also means the oracle contract gets direct access to all underlying calculation contract helper methods

### Key Features

- Obtain all Yearn family asset data in a standardized interface

- Obtain all user asset and token balances/allowances

- Ability to return USDC normalized balances as well as base asset balances

- Obtain various TVL calculations for Yearn

- Total TVL

- TVL per asset type

- TVL per asset

- Integration with all Yearn family protocols

- v1/v2 vaults

- Iron Bank

- Earn

- VeCrv (base contract and pJar)

## Contracts

### Registry Adapters

#### Schema

##### Standardized Interfaces

All registry adapters are required to implement the following interfaces.

###### AdapterMetadata

```
struct AdapterMetadata { string typeId; string categoryId; string subcategoryId;}
```

###### Asset

```
struct Asset { address id; string typeId; string name; string version; uint256 balance; uint256 balanceUsdc; // Asset TVL == balance * token.priceUsdc Token token; AssetMetadata metadata;}
```

###### AssetStatic (static) (not connected)

```
struct AssetStatic { address id; string typeId; string name; string version; Token token;}
```

###### Token (static) (not connected)

```
struct Token { address id; string name; string symbol; uint8 decimals;}
```

```
assetsStatic():[{ id: "0x123...", typeId: "v2Vault", name: "YFI Vault", version: "0.3.2", tokenId: "0x234..." token: { id: "0x234...", name: "yearn.fi", symbol: "YFI", decimals: 18 }}]
```

###### AssetDynamic (dynamic) (not connected)

```
struct AssetDynamic { address assetId; address tokenId; AssetMetadata metadata; TokenAmount underlyingTokenBalance; // Amount of underlying token in the asset}
```

###### TokenAmount (dynamic)

```
struct TokenAmount { uint256 amount; uint256 amountUsdc;}
```

```
assetsDynamic():[{ assetId: "0x123", tokenId: "0x456", metadata: { pricePerShare: "101000022394340034000" }, underlyingTokenBalance: { amount: "53233222334444334444", // vault.totalAssets() amountUsdc: "3422233333445" }}]
```

###### Position (dynamic) (connected)

```
struct Position { address assetId; string typeId; address tokenId; uint256 balance; // asset.balanceOf(account) - shares owned by user TokenPostion underlyingTokenBalance; // Amount of underlying token in the asset that a user owns TokenPosition accountTokenBalance; // Amount of underlying token a user owns Allowance[] tokenAllowances; Allowance[] assetAllowances;}
```

```
positionsOf(account):[{ assetId: "0x123", typeId: "deposit", tokenId: "0x545", balance: "105344343435553", // vault.balanceOf(account) underlyingTokenBalance: { amount: "53233222334444334444", // vault.balanceOf(account) * pricePerShare amountUsdc: "3422233333445" }, accountTokenBalance: { amount: "4424424000238", // token.balanceOf(account) amountUsdc: "23323" }, tokenAllowances: [{ owner: "0x4800", // Account spender: "0x123", // Asset address amount: "115335543535353535235325325325235235325235425235" }], assetAllowances: [{ owner: "0x123", // Asset address spender: "0x456", // Trusted migrator amount: "115335543535353535235325325325235235325235425235" }]}]
```

###### Position

```
struct Position { address assetId; uint256 balance; uint256 balanceUsdc; TokenPosition tokenPosition; Allowance[] allowances;}
```

###### Token

```
struct Token { address id; string name; string symbol; uint8 decimals; uint256 priceUsdc;}
```

###### TokenPosition

```
struct TokenPosition { address tokenId; uint256 balance; uint256 balanceUsdc; Allowance[] allowances;}
```

```
struct Allowance { address owner; address spender; uint256 allowance;}
```

##### Adapter-specific Interfaces

Each registry adapter can export asset metadata that is specific to the asset type.

###### Vault

```
struct AssetMetadata { string symbol; uint256 pricePerShare; bool migrationAvailable; address latestVaultAddress; uint256 depositLimit; bool emergencyShutdown;}
```

###### Earn

`TBD`

###### Iron Bank

`TBD`

###### veCrv

`TBD`

#### Methods

All registry adapters are required to implement the following methods.

##### registryAddress

Get the registry address associated with the adapter. The adapter pulls most information from the registry. `registryAddress` is defined in the adapter consturctor.

```
address public registryAddress;
```

##### assetsLength

Get the number of assets the registry adapter is capable of returning.

```
function assetsLength() public view returns (uint256);
```

`RETURN` Number of registry adapter assets

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);uint256 assetsLength = registryAdapter.assetsLength();
```

###### Example Response

```
32
```

##### positionSpenderAddresses

```
address[] public positionSpenderAddresses;
```

##### setPositionSpenderAddresses

```
function setPositionSpenderAddresses(address addresses)
```

##### assetsAddresses

Get a list of asset addresses from the asset adapter's associated registry.

```
function assetsAddresses() public view returns (address[] memory);
```

`RETURN` Array of asset addresses

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);address[] assetAddresses = registryAdapter.assetsAddresses();
```

###### Example Response

```
['0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1', '0xdCD90C7f6324cfa40d7169ef80b12031770B4325', '0x986b4AFF588a109c09B50A03f42E4110E29D353F', '0xcB550A6D4C8e3517A939BC79d0c7093eb7cF56B5']
```

##### assetTvl

Get TVL for a specific asset (in USDC).

```
function assetTvl(address assetAddress) public view returns (uint256);
```

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);address assetAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;uint256 assetTvl = registryAdapter.assetTvl(assetAddress);
```

###### Example Response

`1637032292`

##### assetsTvl

Get aggregated TVL for all assets in the adapter's registry.

```
function assetsTvl() external view returns (uint256);
```

`RETURN` Aggregated TVL scoped to the adapter's assets in USDC

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);uint256 assetTvl = registryAdapter.assetsTvl();
```

###### Example Response

`443923433354832`

##### asset

Get a specific asset including metadata specific to the asset type. The response extends the standardized `Asset` interface.

```
function asset(address assetAddress) public view returns (Asset memory);
```

`assetAddress` The address of the asset to fetch
`RETURN` An asset struct containing information about the asset

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);address assetAddress = 0xe2F6b9773BF3A015E2aA70741Bde1498bdB9425b;registryAdapter.asset(assetAddress);
```

###### Example Response

```
{ name: 'WTFTM Vault', id: 0xe2F6b9773BF3A015E2aA70741Bde1498bdB9425b, version: '0.3.2', totalAssets: 129999966466476313000000, totalAssetsUsdc: 14355444934422, // TVL metadata: { controller: 0x19D3364A399d251E894aC732651be8B0E4e85001, pricePerShare: 142004300000000000 ... }}
```

##### assets

Get all assets for a registry adapter

```
function assets() external view returns (Asset[] memory);
```

`RETURN` An array of asset structs containing information about the assets

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);registryAdapter.assets();
```

###### Example Response

```
[ { name: 'WFTM Vault', id: 0xe2F6b9773BF3A015E2aA70741Bde1498bdB9425b, // vault address version: '0.3.2', totalAssets: 129999966466476313000000, totalAssetsUsdc: 14355444934422, // TVL metadata: { controller: 0x19D3364A399d251E894aC732651be8B0E4e85001, pricePerShare: 142004300000000000 ... } }, { name: 'fUSD Vault', id: 0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9, version: '0.3.2', totalAssets: 4593326846642963130309078, totalAssetsUsdc: 45444930943854422, // TVL metadata: { controller: 0x19D3364A399d251E894aC732651be8B0E4e85001, pricePerShare: 101003300000000000 ... } }]
```

##### positionOf

Get the position of an account for a specific asset address.

```
function positionOf(address accountAddress, address assetAddress) public view returns (Position memory);
```

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);address accountAddress = 0x481140F916a4e64559694DB4d56D692CadC0326c;address assetAddress = 0xe2F6b9773BF3A015E2aA70741Bde1498bdB9425b;registryAdapter.positionForAsset(accountAddress, assetAddress);
```

###### Example Response

```
{ assetId: 0xe2F6b9773BF3A015E2aA70741Bde1498bdB9425b, // vault address depositedBalance: 10422000000000000000, depositedBalanceUsdc: 10422000, tokenBalance: 2110000000000000000, tokenBalanceUsdc: 2110000, tokenAllowance, 1157343987545498574545495749587452... // max uint256}
```

##### positionsOf

Get all positions for an account for every adapter asset.

```
function positionsOf(address accountAddress) external view returns (Position[] memory);
```

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);address accountAddress = 0x481140F916a4e64559694DB4d56D692CadC0326c;registryAdapter.positionsOf(accountAddress);
```

###### Example Response

```
[ { assetId: 0xe2F6b9773BF3A015E2aA70741Bde1498bdB9425b, // vault address depositedBalance: 10422000000000000000, depositedBalanceUsdc: 10422000, tokenBalance: 2110000000000000000, tokenBalanceUsdc: 2110000, tokenAllowance, 1157343987545498574545495749587452... // max uint256 }, { assetId: 0x19D3364A399d251E894aC732651be8B0E4e85001, // vault address depositedBalance: 10422000000000000000, depositedBalanceUsdc: 10422000, tokenBalance: 0, tokenBalanceUsdc: 0, tokenAllowance, 0 }]
```

##### tokens

Get unique tokens for the adapter.

```
function tokens() external view returns (Token[] memory);
```

###### Solidity

```
RegistryAdapter registryAdapter = RegistryAdapter(0xABCD...);registryAdapter.tokens();
```

###### Example Response

```
[ { id: 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, // token address name: 'USD Coin', symbol: 'USDC', decimals: 18, priceUsdc: 100000 }, ...]
```

### Oracle

#### Methods

##### setCalculations

Set oracle calculation contract addresses. Each calculation contract must implement getPriceUsdc(). The order of calculation contracts matters as it determines the order preference in the cascading fallback mechanism.

```
function setCalculations(address[] memory calculationAddresses) public onlyManagers;
```

`calculationAddresses` An array of addresses for underlying calculation contracts

##### calculations

View the calculation contract addresses currently associated with the oracle.

```
function calculations() external view returns (address[] memory);
```

`RETURN` An array of calculation contract addresses associated with the oracle

###### Example Response

```
[ "0xfC714174E5c8bd056a45a5337E7b402CC4af7BF3", "0x55e9B18fefFF7E00548d54480373Fc8843De8eA4", "0x88dE7d7F7b9597C86b8cD195374FbF602934F334"]
```

##### getPriceUsdcRecommended

Get the currently recommended price given a token address.

```
function getPriceUsdcRecommended(address tokenAddress) public view returns (uint256);
```

`tokenAddress` The token address for which to obtain a price recommendation
`RETURN` Recommended price in USDC (6 decimals)

###### Example Response

`103000`

##### getNormalizedValueUsdc

Calculate normalized USDC value given a token address and an amount.

```
function getNormalizedValueUsdc(address tokenAddress, uint256 amount) external view returns (uint256);
```

`tokenAddress` The token address
`amount` The amount of value to convert (in token decimals)
`RETURN` Recommended price in USDC (6 decimals)

###### Example Response

`3442238822`

##### tokenAliases

Given a token address fetch a token alias address. This is necessary for certain wrapped or special case tokens that do not have a token price available in the oracle.

```
mapping(address => address) public tokenAliases;
```

##### addTokenAlias

Add a new token alias mapping.

```
function addTokenAlias(address tokenAddress, address tokenAliasAddress) public onlyManagers;
```

`tokenAddress` The token address that will receive an alias
`tokenAliasAddress` The new token alias address

##### addTokenAliases

Batch add new token alias mappingings.

```
function addTokenAliases(TokenAlias[] memory tokenAliases) public onlyManagers
```

`tokenAliases` An array of `TokenAlias` structs (`[[tokenAddress, tokenAliasAddress]]`)

##### removeTokenAlias

Remove a token alias mapping.

```
function addTokenAlias(address tokenAddress, address tokenAliasAddress) public onlyManagers;
```

`tokenAddress` The token address whose alias will be removed

### Calculation

#### Standardized methods

All calculation contracts must implement the following methods.

##### getPriceUsdc

Fetch the recommended price given a token address. Reverts if no relevant price is found.

```
function getPriceUsdc(address tokenAddress) public view returns (uint256)
```

###### Example Response

`103000`

#### Calculation specific methods

Helper utilities for various calculations. These methods are indirectly exposed to the oracle via the oracle's cascading fallback mechanism. All of these methods can be called via the oracle contract by generating a custom ABI with the desired methods. Since these helper methods do not represent the primary use case of the oracle contract (the primary use case is fetching price) determining the details of each method implementation is left to the user.

##### Sushiswap

```
function getPriceFromRouter(address token0Address, address token1Address) public view returns (uint256);function getPriceFromRouterUsdc(address tokenAddress) public view returns (uint256);function isLpToken(address tokenAddress) public view returns (bool);function getRouterForLpToken(address tokenAddress) public view returns (PriceRouter);function getLpTokenTotalLiquidityUsdc(address tokenAddress) public view returns (uint256);function getLpTokenPriceUsdc(address tokenAddress) public view returns (uint256);
```

##### Curve

```
function getBasePrice(address curveLpTokenAddress) public view returns (uint256);function getVirtualPrice(address curveLpTokenAddress) public view returns (uint256);function isCurveLpToken(address tokenAddress) public view returns (bool);function getFirstUnderlyingCoinFromPool(address poolAddress) public view returns (address);function getCurvePriceUsdc(address curveLpTokenAddress) public view returns (uint256);
```

##### IronBank

```
function isIronBankMarket(address tokenAddress) public view returns (bool);function getIronBankMarkets() public view returns (address[] memory);function getIronBankMarketPriceUsdc(address tokenAddress) public view returns (uint256);
```

### Lens

#### Methods

##### addAdapter

Add a registry adapter. The registry adapter must conform to the standardized registry adapter interface.

```
function addAdapter(address adapterAddress) public onlyManager;
```

`adapterAddress` Address of the adapter to add

###### Solidity

```
Lens lens = Lens(0x9b8b9F6146B29CC32208f42b995E70F0Eb2807F3);address adapterAddress = 0xe11ba472F74869176652C35D30dB89854b5ae84D;lens.addAdapter(adapterAddress);
```

##### removeAdapter

Remove a registry adapter.

```
function removeAdapter(address adapterAddress) public onlyManager;
```

`adapterAddress` Address of the adapter to remove

###### Solidity

```
Lens lens = Lens(0x9b8b9F6146B29CC32208f42b995E70F0Eb2807F3);address adapterAddress = 0xe11ba472F74869176652C35D30dB89854b5ae84D;lens.removeAdapter(adapterAddress);
```

##### adapters

Fetch a list of registry adapter addresses.

```
function adapters() external view returns (address[] memory);
```

###### Solidity

```
Lens lens = Lens(0x9b8b9F6146B29CC32208f42b995E70F0Eb2807F3);address[] memory = lens.adapters();
```

###### Example Response

```
['0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1', '0xdCD90C7f6324cfa40d7169ef80b12031770B4325', '0x986b4AFF588a109c09B50A03f42E4110E29D353F', '0xcB550A6D4C8e3517A939BC79d0c7093eb7cF56B5']
```

##### assetsFromAdapter

```
function assetsFromAdapter(RegistryAdapter registryAdapterAddress) external view returns (RegistryAdapter.Asset[] memory)
```

See: registryAdapter.assets (https://docs.yearn.fi/developers/smart-contracts/deprecated/V2/version-0.4.5/yearn-lens/#assets)

##### assets

Fetch all assets for all supported protocols.

```
function assets() external view returns (RegistryAdapter.Asset[] memory)
```

See: registryAdapter.assets (https://docs.yearn.fi/developers/smart-contracts/deprecated/V2/version-0.4.5/yearn-lens/#assets)

##### positionsFromAdapter

Fetch positions for an account for a specific adapter.

```
function positionsFromAdapter( address account, RegistryAdapter registryAdapterAddress ) external view returns (RegistryAdapter.Position[] memory)
```

See: registryAdapter.positionsOf (https://docs.yearn.fi/developers/smart-contracts/deprecated/V2/version-0.4.5/yearn-lens/#positionof)

##### positionsOf

Fetch all positions for an account within the ecosystem.

```
function positionsOf(address account) external view returns (RegistryAdapter.Position[] memory)
```

See: registryAdapter.positionsOf (https://docs.yearn.fi/developers/smart-contracts/deprecated/V2/version-0.4.5/yearn-lens/#positionof)

##### assetsLength

```
function assetsLength() public view returns (uint256);
```

Get the total number of assets for all Yearn family protocols
See: registryAdapter.assetsLength (https://docs.yearn.fi/developers/smart-contracts/deprecated/V2/version-0.4.5/yearn-lens/#assetslength)

##### assetsAddresses

```
function assetsAddresses() public view returns (address[] memory);
```

Get all addresses for all Yearn family assets
See: registryAdapter.assetsAddresses (https://docs.yearn.fi/developers/smart-contracts/deprecated/V2/version-0.4.5/yearn-lens/#assetsaddresses)

##### allowances

Batch fetch allowances given an owner, tokens and spender. This is a helper utility for fetching large amounts of token allowances for a specific set of contracts

```
function allowances( address owner, address[] memory tokens, address[] memory spenders ) external view returns (uint256[] memory)
```


Yearn API

Yearn API

Production Endpoint

API Schema

# Yearn API

### Production Endpoint

https://ydaemon.yearn.fi/1/vaults/all

### API Schema

FieldDescription`address`Checksummed address of the vault`inception`The block number a vault was created at`symbol`Vault token symbol (used primarily in metamask)`name`Vault token name`display_name`Vault name as displayed in UI (usually based on underlying symbol)`icon`Vault token icon url`token`Underlying vault token metadata`token.name`Underlying token name`token.symbol`Underlying token symbol`token.address`Underlying token address`token.decimals`Underlying token decimal amount`token.display_name`Underlying token display name`token.icon`Underlying token icon (usually used as vault dispaly icon)`tvl`TVL information about a vault`tvl.total_assets`TVL in underlying token denomination`tvl.price`Token price in USD`tvl.tvl`TVL in USD`apy`Vault APY metadata`apy.type`APY type. Options are `v2:simple`, `v2:averaged`, `v1:simple`, `crv``apy.gross_apr`Uncompounded gross APR before fees`apy.net_apy`Net APY (compounded) after fees. This is what the UI shows`apy.fees`Fee structure breakdown for a vault`apy.fees.performance`Performance fee in bips`apy.fees.withdrawal`Withdrawal fee in bips`apy.fees.management`Management fee in bips`apy.fees.keep_crv`Amount of CRV to keep upon harvest for curve vaults in bips`apy.fees.cvx_keep_crv`Amount of CRV to keep upon harvest for curve convex vaults in bips`apy.points`APY samples for various timeframes`apy.points.week_ago`APY calculated from one week sample of pricePerShare`apy.points.month_ago`APY calculated from one month sample of pricePerShare`apy.points.month_ago`APY calculated from inception block sample of pricePerShare`apy.composite`Complex APY breakdown (for curve vaults)`apy.composite.boost`Current boost of the strategies`apy.composite.pool_apy`APY of the Curve LP position`apy.composite.base_apr`Base APR of Curve emissions`apy.composite.boosted_apr`Boosted APR of Curve emissions`apy.composite.cvx_apr`APR of Convex rewards`apy.composite.rewards_apr`APR of additional pool rewards`strategies`A list of active vault strategies`strategies[idx].address`Address of an active strategy`strategies[idx].name`Name of an active strategy`endorsed`True if the vault is an endorsed production vault. Do not show the vault if it's not endorsed`version`API version of the vault`decimals`Number of decimals for the vault token`type`High level vault classification. Valid options are v1 and v2`emergency_shutdown`If true the vault is in shut down mode and no new deposits should be accepted`updated`Unix timestamp of the last vault update


BaseStrategy

BaseStrategy

Functions

apiVersion

Return Values:

name

Return Values:

delegatedAssets

constructor

Parameters:

setHealthCheck

setDoHealthCheck

setStrategist

Parameters:

setKeeper

Parameters:

setRewards

Parameters:

setMinReportDelay

Parameters:

setMaxReportDelay

Parameters:

setCreditThreshold

Parameters:

setForceHarvestTriggerOnce

Parameters:

setBaseFeeOracle

Parameters:

setMetadataURI

Parameters:

governance

ethToWant

Parameters:

Return Values:

estimatedTotalAssets

Return Values:

isActive

prepareReturn

adjustPosition

liquidatePosition

liquidateAllPositions

tendTrigger

Parameters:

Return Values:

tend

harvestTrigger

Parameters:

Return Values:

isBaseFeeAcceptable

Return Values:

harvest

withdraw

Parameters:

Return Values:

prepareMigration

migrate

Parameters:

setEmergencyExit

protectedTokens

sweep

Parameters:

Events

Harvested

UpdatedStrategist

UpdatedKeeper

UpdatedRewards

UpdatedMinReportDelay

UpdatedMaxReportDelay

UpdatedBaseFeeOracle

UpdatedCreditThreshold

ForcedHarvestTrigger

EmergencyExitEnabled

UpdatedMetadataURI

SetHealthCheck

SetDoHealthCheck

# BaseStrategy

## Functions

### apiVersion

```
function apiVersion( ) public returns (string)
```

Used to track which version of `StrategyAPI` this Strategy
implements.

The Strategy's version must match the Vault's `API_VERSION`.

#### Return Values:

NameTypeDescription`A`string which holds the current API version of this contract.

### name

```
function name( ) external returns (string)
```

This Strategy's name.

@dev
You can use this field to manage the "version" of this Strategy, e.g.
`StrategySomethingOrOtherV1`. However, "API Version" is managed by
`apiVersion()` function above.

#### Return Values:

NameTypeDescription`This`Strategy's name.

### delegatedAssets

```
function delegatedAssets( ) external returns (uint256)
```

The amount (priced in want) of the total assets managed by this strategy should not count
towards Yearn's TVL calculations.

@dev
You can override this field to set it to a non-zero value if some of the assets of this
Strategy is somehow delegated inside another part of Yearn's ecosystem e.g. another Vault.
Note that this value must be strictly less than or equal to the amount provided by
`estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
Also note that this value is used to determine the total assets under management by this
strategy, for the purposes of computing the management fee in `Vault`

@return
The amount of assets this strategy manages that should not be included in Yearn's Total Value
Locked (TVL) calculation across it's ecosystem.

### _onlyAuthorized

```
function _onlyAuthorized( ) internal
```

### _onlyEmergencyAuthorized

```
function _onlyEmergencyAuthorized( ) internal
```

### _onlyStrategist

```
function _onlyStrategist( ) internal
```

### _onlyGovernance

```
function _onlyGovernance( ) internal
```

### _onlyRewarder

```
function _onlyRewarder( ) internal
```

### _onlyKeepers

```
function _onlyKeepers( ) internal
```

### _onlyVaultManagers

```
function _onlyVaultManagers( ) internal
```

### constructor

```
function constructor( ) internal
```

### _initialize

```
function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal
```

Initializes the Strategy, this is called only once, when the
contract is deployed.

`_vault` should implement `VaultAPI`.

#### Parameters:

NameTypeDescription`_vault`addressThe address of the Vault responsible for this Strategy.`_strategist`addressThe address to assign as `strategist`.The strategist is able to change the reward address`_rewards`addressThe address to use for pulling rewards.`_keeper`addressThe adddress of the _keeper. _keepercan harvest and tend a strategy.

### setHealthCheck

```
function setHealthCheck( ) external
```

### setDoHealthCheck

```
function setDoHealthCheck( ) external
```

### setStrategist

```
function setStrategist( address _strategist ) external
```

Used to change `strategist`.

This may only be called by governance or the existing strategist.

#### Parameters:

NameTypeDescription`_strategist`addressThe new address to assign as `strategist`.

### setKeeper

```
function setKeeper( address _keeper ) external
```

Used to change `keeper`.

`keeper` is the only address that may call `tend()` or `harvest()`,
other than `governance()` or `strategist`. However, unlike
`governance()` or `strategist`, `keeper` may only call `tend()`
and `harvest()`, and no other authorized functions, following the
principle of least privilege.

This may only be called by governance or the strategist.

#### Parameters:

NameTypeDescription`_keeper`addressThe new address to assign as `keeper`.

### setRewards

```
function setRewards( address _rewards ) external
```

Used to change `rewards`. EOA or smart contract which has the permission
to pull rewards from the vault.

This may only be called by the strategist.

#### Parameters:

NameTypeDescription`_rewards`addressThe address to use for pulling rewards.

### setMinReportDelay

```
function setMinReportDelay( uint256 _delay ) external
```

Used to change `minReportDelay`. `minReportDelay` is the minimum number
of blocks that should pass for `harvest()` to be called.

For external keepers (such as the Keep3r network), this is the minimum
time between jobs to wait. (see `harvestTrigger()`
for more details.)

This may only be called by governance or the strategist.

#### Parameters:

NameTypeDescription`_delay`uint256The minimum number of seconds to wait between harvests.

### setMaxReportDelay

```
function setMaxReportDelay( uint256 _delay ) external
```

Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
of blocks that should pass for `harvest()` to be called.

For external keepers (such as the Keep3r network), this is the maximum
time between jobs to wait. (see `harvestTrigger()`
for more details.)

This may only be called by governance or the strategist.

#### Parameters:

NameTypeDescription`_delay`uint256The maximum number of seconds to wait between harvests.

### setCreditThreshold

```
function setCreditThreshold( uint256 _creditThreshold ) external
```

Used to ensure that any significant credit a strategy has from the
vault will be automatically harvested.

This may only be called by governance or management.

#### Parameters:

NameTypeDescription`_creditThreshold`uint256The number of want tokens that willautomatically trigger a harvest.

### setForceHarvestTriggerOnce

```
function setForceHarvestTriggerOnce( bool _forceHarvestTriggerOnce ) external
```

Used to automatically trigger a harvest by our keepers. Can be
useful if gas prices are too high now, and we want to harvest
later once prices have lowered.

This may only be called by governance or management.

#### Parameters:

NameTypeDescription`_forceHarvestTriggerOnce`boolValue of true tells keepers to harvestour strategy

### setBaseFeeOracle

```
function setBaseFeeOracle( address _baseFeeOracle ) external
```

Used to set our baseFeeOracle, which checks the network's current base
fee price to determine whether it is an optimal time to harvest or tend.

This may only be called by governance or management.

#### Parameters:

NameTypeDescription`_baseFeeOracle`addressAddress of our baseFeeOracle

### setMetadataURI

```
function setMetadataURI( string _metadataURI ) external
```

Used to change `metadataURI`. `metadataURI` is used to store the URI
of the file describing the strategy.

This may only be called by governance or the strategist.

#### Parameters:

NameTypeDescription`_metadataURI`stringThe URI that describe the strategy.

### governance

```
function governance( ) internal returns (address)
```

Resolve governance address from Vault contract, used to make assertions
on protected functions in the Strategy.

### ethToWant

```
function ethToWant( uint256 _amtInWei ) public returns (uint256)
```

Provide an accurate conversion from `_amtInWei` (denominated in wei)
to `want` (using the native decimal characteristics of `want`).

@dev
Care must be taken when working with decimals to assure that the conversion
is compatible. As an example:

given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)

#### Parameters:

NameTypeDescription`_amtInWei`uint256The amount (in wei/1e-18 ETH) to convert to `want`

#### Return Values:

NameTypeDescription`The`uint256amount in `want` of `_amtInEth` converted to `want`

### estimatedTotalAssets

```
function estimatedTotalAssets( ) public returns (uint256)
```

Provide an accurate estimate for the total amount of assets
(principle + return) that this Strategy is currently managing,
denominated in terms of `want` tokens.

This total should be "realizable" e.g. the total value that could
actually be obtained from this Strategy if it were to divest its
entire position based on current on-chain conditions.

@dev
Care must be taken in using this function, since it relies on external
systems, which could be manipulated by the attacker to give an inflated
(or reduced) value produced by this function, based on current on-chain
conditions (e.g. this function is possible to influence through
flashloan attacks, oracle manipulations, or other DeFi attack
mechanisms).

It is up to governance to use this function to correctly order this
Strategy relative to its peers in the withdrawal queue to minimize
losses for the Vault based on sudden withdrawals. This value should be
higher than the total debt of the Strategy and higher than its expected
value to be "safe".

#### Return Values:

NameTypeDescription`The`estimated total assets in this Strategy.

### isActive

```
function isActive( ) public returns (bool)
```

### prepareReturn

```
function prepareReturn( ) internal returns (uint256 _profit, uint256 _loss, uint256 _debtPayment)
```

Perform any Strategy unwinding or other calls necessary to capture the
"free return" this Strategy has generated since the last time its core
position(s) were adjusted. Examples include unwrapping extra rewards.
This call is only used during "normal operation" of a Strategy, and
should be optimized to minimize losses as much as possible.

This method returns any realized profits and/or realized losses
incurred, and should return the total amounts of profits/losses/debt
payments (in `want` tokens) for the Vault's accounting (e.g.
`want.balanceOf(this) >= _debtPayment + _profit`).

`_debtOutstanding` will be 0 if the Strategy is not past the configured
debt limit, otherwise its value will be how far past the debt limit
the Strategy is. The Strategy's debt limit is configured in the Vault.

NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
It is okay for it to be less than `_debtOutstanding`, as that
should only used as a guide for how much is left to pay back.
Payments should be made to minimize loss from slippage, debt,
withdrawal fees, etc.

See `vault.debtOutstanding()`.

### adjustPosition

```
function adjustPosition( ) internal
```

Perform any adjustments to the core position(s) of this Strategy given
what change the Vault made in the "investable capital" available to the
Strategy. Note that all "free capital" in the Strategy after the report
was made is available for reinvestment. Also note that this number
could be 0, and you should handle that scenario accordingly.

See comments regarding `_debtOutstanding` on `prepareReturn()`.

### liquidatePosition

```
function liquidatePosition( ) internal returns (uint256 _liquidatedAmount, uint256 _loss)
```

Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
This function should return the amount of `want` tokens made available by the
liquidation. If there is a difference between them, `_loss` indicates whether the
difference is due to a realized loss, or if there is some other sitution at play
(e.g. locked funds) where the amount made available is less than what is needed.

NOTE: The invariant `_liquidatedAmount + _loss NameTypeDescription`callCostInWei`uint256The keeper's estimated gas cost to call `tend()` (in wei).

#### Return Values:

NameTypeDescription`if`uint256`tend()` should be called, `false` otherwise.

### tend

```
function tend( ) external
```

Adjust the Strategy's position. The purpose of tending isn't to
realize gains, but to maximize yield by reinvesting any returns.

See comments on `adjustPosition()`.

This may only be called by governance, the strategist, or the keeper.

### harvestTrigger

```
function harvestTrigger( uint256 callCostInWei ) public returns (bool)
```

Provide a signal to the keeper that `harvest()` should be called. The
keeper will provide the estimated gas cost that they would pay to call
`harvest()`, and this function should use that estimate to make a
determination if calling it is "worth it" for the keeper. This is not
the only consideration into issuing this trigger, for example if the
position would be negatively affected if `harvest()` is not called
shortly, then this can return `true` even if the keeper might be "at a
loss" (keepers are always reimbursed by Yearn).

@dev
`callCostInWei` must be priced in terms of `wei` (1e-18 ETH).

This call and `tendTrigger` should never return `true` at the
same time.

See `maxReportDelay`, `creditThreshold` to adjust the
strategist-controlled parameters that will influence whether this call
returns `true` or not. These parameters will be used in conjunction
with the parameters reported to the Vault (see `params`) to determine
if calling `harvest()` is merited.

This trigger also checks the network's base fee to avoid harvesting during
times of high network congestion.

Consider use of super.harvestTrigger() in any override to build on top
of this logic instead of replacing it. For example, if using `minReportDelay`.

It is expected that an external system will check `harvestTrigger()`.
This could be a script run off a desktop or cloud bot (e.g.
https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
or via an integration with the Keep3r network (e.g.
https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).

#### Parameters:

NameTypeDescription`callCostInWei`uint256The keeper's estimated gas cost to call `harvest()` (in wei).

#### Return Values:

NameTypeDescription`if`uint256`harvest()` should be called, `false` otherwise.

### isBaseFeeAcceptable

```
function isBaseFeeAcceptable( ) public returns (bool)
```

Check if the current network base fee is below our external target. If
not, then harvestTrigger will return false.

#### Return Values:

NameTypeDescription`if``harvest()` should be allowed, `false` otherwise.

### harvest

```
function harvest( ) external
```

Harvests the Strategy, recognizing any profits or losses and adjusting
the Strategy's position.

In the rare case the Strategy is in emergency shutdown, this will exit
the Strategy's position.

This may only be called by governance, the strategist, or the keeper.

@dev
When `harvest()` is called, the Strategy reports to the Vault (via
`vault.report()`), so in some cases `harvest()` must be called in order
to take in profits, to borrow newly available funds from the Vault, or
otherwise adjust its position. In other cases `harvest()` must be
called to report to the Vault on the Strategy's position, especially if
any losses have occurred.

### withdraw

```
function withdraw( uint256 _amountNeeded ) external returns (uint256 _loss)
```

Withdraws `_amountNeeded` to `vault`.

This may only be called by the Vault.

#### Parameters:

NameTypeDescription`_amountNeeded`uint256How much `want` to withdraw.

#### Return Values:

NameTypeDescription`_loss`uint256Any realized losses

### prepareMigration

```
function prepareMigration( ) internal
```

Do anything necessary to prepare this Strategy for migration, such as
transferring any reserve or LP tokens, CDPs, or other tokens or stores of
value.

### migrate

```
function migrate( address _newStrategy ) external
```

Transfers all `want` from this Strategy to `_newStrategy`.

This may only be called by the Vault.

@dev
The new Strategy's Vault must be the same as this Strategy's Vault.
The migration process should be carefully performed to make sure all
the assets are migrated to the new address, which should have never
interacted with the vault before.

#### Parameters:

NameTypeDescription`_newStrategy`addressThe Strategy to migrate to.

### setEmergencyExit

```
function setEmergencyExit( ) external
```

Activates emergency exit. Once activated, the Strategy will exit its
position upon the next harvest, depositing all funds into the Vault as
quickly as is reasonable given on-chain conditions.

This may only be called by governance or the strategist.

@dev
See `vault.setEmergencyShutdown()` and `harvest()` for further details.

### protectedTokens

```
function protectedTokens( ) internal returns (address[])
```

Override this to add all tokens/tokenized positions this contract
manages on a persistent basis (e.g. not just for swapping back to
want ephemerally).

NOTE: Do not include `want`, already included in `sweep` below.

Example:

```
function protectedTokens() internal override view returns (address[] memory) { address[] memory protected = new address[](3); protected[0] = tokenA; protected[1] = tokenB; protected[2] = tokenC; return protected; }
```

### sweep

```
function sweep( address _token ) external
```

Removes tokens from this Strategy that are not the type of tokens
managed by this Strategy. This may be used in case of accidentally
sending the wrong kind of token to this Strategy.

Tokens will be sent to `governance()`.

This will fail if an attempt is made to sweep `want`, or any tokens
that are protected by this Strategy.

This may only be called by governance.

@dev
Implement `protectedTokens()` to specify any additional tokens that
should be protected from sweeping in addition to `want`.

#### Parameters:

NameTypeDescription`_token`addressThe token to transfer out of this vault.

## Events

### Harvested

```
event Harvested( )
```

### UpdatedStrategist

```
event UpdatedStrategist( )
```

### UpdatedKeeper

```
event UpdatedKeeper( )
```

### UpdatedRewards

```
event UpdatedRewards( )
```

### UpdatedMinReportDelay

```
event UpdatedMinReportDelay( )
```

### UpdatedMaxReportDelay

```
event UpdatedMaxReportDelay( )
```

### UpdatedBaseFeeOracle

```
event UpdatedBaseFeeOracle( )
```

### UpdatedCreditThreshold

```
event UpdatedCreditThreshold( )
```

### ForcedHarvestTrigger

```
event ForcedHarvestTrigger( )
```

### EmergencyExitEnabled

```
event EmergencyExitEnabled( )
```

### UpdatedMetadataURI

```
event UpdatedMetadataURI( )
```

### SetHealthCheck

```
event SetHealthCheck( )
```

### SetDoHealthCheck

```
event SetDoHealthCheck( )
```


BaseStrategyInitializable

BaseStrategyInitializable

Functions

constructor

initialize

clone

clone

Events

Cloned

# BaseStrategyInitializable

## Functions

### constructor

```
function constructor( ) internal
```

### initialize

```
function initialize( ) external
```

### clone

```
function clone( ) external returns (address)
```

### clone

```
function clone( ) public returns (address newStrategy)
```

## Events

### Cloned

```
event Cloned( )
```


BaseFeeOracle

BaseFeeOracle

Functions

constructor

isCurrentBaseFeeAcceptable

setMaxAcceptableBaseFee

Parameters:

setManualBaseFeeBool

Parameters:

setAuthorized

Parameters:

setPendingGovernance

Parameters:

acceptGovernance

setBaseFeeProvider

Parameters:

Events

NewGovernance

NewProvider

UpdatedMaxBaseFee

UpdatedManualBaseFee

UpdatedAuthorization

# BaseFeeOracle

Interprets the base fee from our base fee provider
contract to determine if a harvest is permissable.

Version 0.1.0

## Functions

### constructor

```
function constructor( ) public
```

Use this if our network hasn't implemented the base fee method yet

### isCurrentBaseFeeAcceptable

```
function isCurrentBaseFeeAcceptable( ) public returns (bool)
```

Returns whether we should allow harvests based on current base fee.

### setMaxAcceptableBaseFee

```
function setMaxAcceptableBaseFee( uint256 _maxAcceptableBaseFee ) external
```

Set the maximum base fee we want for our keepers to accept.
Gwei is 1e9.

Throws if the caller is not authorized or gov.

#### Parameters:

NameTypeDescription`_maxAcceptableBaseFee`uint256The acceptable maximum price to pay in wei.

### setManualBaseFeeBool

```
function setManualBaseFeeBool( bool _manualBaseFeeBool ) external
```

If we don't have a provider, then manually determine if true or not.
Useful in testing as well.

Throws if the caller is not authorized or gov.

#### Parameters:

NameTypeDescription`_manualBaseFeeBool`boolBoolean to allow/block harvests if we don'thave a provider set up.

### setAuthorized

```
function setAuthorized( address _target, bool _value ) external
```

Controls whether a non-gov address can adjust certain params.

Throws if the caller is not current governance.

#### Parameters:

NameTypeDescription`_target`addressThe address to add/remove authorization for.`_value`boolBoolean to grant or revoke access.

### setPendingGovernance

```
function setPendingGovernance( address _governance ) external
```

Starts the 1st phase of the governance transfer.

Throws if the caller is not current governance.

#### Parameters:

NameTypeDescription`_governance`addressThe next governance address

### acceptGovernance

```
function acceptGovernance( ) external
```

Completes the 2nd phase of the governance transfer.

Throws if the caller is not the pending caller.
Emits a `NewGovernance` event.

### setBaseFeeProvider

```
function setBaseFeeProvider( address _baseFeeProvider ) external
```

Sets the address used to pull the current network base fee.

Throws if the caller is not current governance.

#### Parameters:

NameTypeDescription`_baseFeeProvider`addressThe network's baseFeeProvider address

### _onlyAuthorized

```
function _onlyAuthorized( ) internal
```

### _onlyGovernance

```
function _onlyGovernance( ) internal
```

## Events

### NewGovernance

```
event NewGovernance( )
```

### NewProvider

```
event NewProvider( )
```

### UpdatedMaxBaseFee

```
event UpdatedMaxBaseFee( )
```

### UpdatedManualBaseFee

```
event UpdatedManualBaseFee( )
```

### UpdatedAuthorization

```
event UpdatedAuthorization( )
```


VaultAPI

VaultAPI

Functions

name

symbol

decimals

apiVersion

permit

deposit

deposit

deposit

withdraw

withdraw

withdraw

token

strategies

pricePerShare

totalAssets

depositLimit

maxAvailableShares

creditAvailable

debtOutstanding

expectedReturn

report

revokeStrategy

governance

management

guardian

# VaultAPI

## Functions

### name

```
function name( ) external returns (string)
```

### symbol

```
function symbol( ) external returns (string)
```

### decimals

```
function decimals( ) external returns (uint256)
```

### apiVersion

```
function apiVersion( ) external returns (string)
```

### permit

```
function permit( ) external returns (bool)
```

### deposit

```
function deposit( ) external returns (uint256)
```

### deposit

```
function deposit( ) external returns (uint256)
```

### deposit

```
function deposit( ) external returns (uint256)
```

### withdraw

```
function withdraw( ) external returns (uint256)
```

### withdraw

```
function withdraw( ) external returns (uint256)
```

### withdraw

```
function withdraw( ) external returns (uint256)
```

### token

```
function token( ) external returns (address)
```

### strategies

```
function strategies( ) external returns (struct StrategyParams)
```

### pricePerShare

```
function pricePerShare( ) external returns (uint256)
```

### totalAssets

```
function totalAssets( ) external returns (uint256)
```

### depositLimit

```
function depositLimit( ) external returns (uint256)
```

### maxAvailableShares

```
function maxAvailableShares( ) external returns (uint256)
```

### creditAvailable

```
function creditAvailable( ) external returns (uint256)
```

View how much the Vault would increase this Strategy's borrow limit,
based on its present performance (since its last report). Can be used to
determine expectedReturn in your Strategy.

### debtOutstanding

```
function debtOutstanding( ) external returns (uint256)
```

View how much the Vault would like to pull back from the Strategy,
based on its present performance (since its last report). Can be used to
determine expectedReturn in your Strategy.

### expectedReturn

```
function expectedReturn( ) external returns (uint256)
```

View how much the Vault expect this Strategy to return at the current
block, based on its present performance (since its last report). Can be
used to determine expectedReturn in your Strategy.

### report

```
function report( ) external returns (uint256)
```

This is the main contact point where the Strategy interacts with the
Vault. It is critical that this call is handled as intended by the
Strategy. Therefore, this function will be called by BaseStrategy to
make sure the integration is correct.

### revokeStrategy

```
function revokeStrategy( ) external
```

This function should only be used in the scenario where the Strategy is
being retired but no migration of the positions are possible, or in the
extreme scenario that the Strategy needs to be put into "Emergency Exit"
mode in order for it to exit as quickly as possible. The latter scenario
could be for any reason that is considered "critical" that the Strategy
exits its position as fast as possible, such as a sudden change in
market conditions leading to losses, or an imminent failure in an
external dependency.

### governance

```
function governance( ) external returns (address)
```

View the governance address of the Vault to assert privileged functions
can only be called by governance. The Strategy serves the Vault, so it
is subject to governance defined by the Vault.

### management

```
function management( ) external returns (address)
```

View the management address of the Vault to assert privileged functions
can only be called by management. The Strategy serves the Vault, so it
is subject to management defined by the Vault.

### guardian

```
function guardian( ) external returns (address)
```

View the guardian address of the Vault to assert privileged functions
can only be called by guardian. The Strategy serves the Vault, so it
is subject to guardian defined by the Vault.


Vault.vy

Vault.vy

Functions

initialize

Parameters:

initialize

Parameters:

initialize

Parameters:

apiVersion

Return Values:

setName

Parameters:

setSymbol

Parameters:

setGovernance

Parameters:

acceptGovernance

setManagement

Parameters:

setRewards

Parameters:

setLockedProfitDegradation

Parameters:

setDepositLimit

Parameters:

setPerformanceFee

Parameters:

setManagementFee

Parameters:

setGuardian

Parameters:

setEmergencyShutdown

Parameters:

setWithdrawalQueue

Parameters:

transfer

Parameters:

Return Values:

transferFrom

Parameters:

Return Values:

approve

Parameters:

increaseAllowance

Parameters:

decreaseAllowance

Parameters:

permit

Parameters:

Return Values:

totalAssets

Return Values:

deposit

Parameters:

Return Values:

deposit

Parameters:

Return Values:

deposit

Parameters:

Return Values:

maxAvailableShares

Return Values:

withdraw

Parameters:

Return Values:

withdraw

Parameters:

Return Values:

withdraw

Parameters:

Return Values:

withdraw

Parameters:

Return Values:

pricePerShare

Return Values:

addStrategy

Parameters:

updateStrategyDebtRatio

Parameters:

updateStrategyMinDebtPerHarvest

Parameters:

updateStrategyMaxDebtPerHarvest

Parameters:

updateStrategyPerformanceFee

Parameters:

migrateStrategy

Parameters:

revokeStrategy

Parameters:

revokeStrategy

Parameters:

addStrategyToQueue

Parameters:

removeStrategyFromQueue

Parameters:

debtOutstanding

Parameters:

Return Values:

debtOutstanding

Parameters:

Return Values:

creditAvailable

Parameters:

Return Values:

creditAvailable

Parameters:

Return Values:

expectedReturn

Parameters:

Return Values:

expectedReturn

Parameters:

Return Values:

report

Parameters:

Return Values:

sweep

Parameters:

sweep

Parameters:

Events

# Vault.vy

Yearn Token Vault

Yearn Token Vault. Holds an underlying token, and allows users to interact with the Yearn ecosystem through Strategies connected to the Vault. Vaults are not limited to a single Strategy, they can have as many Strategies as can be designed (however the withdrawal queue is capped at 20.) Deposited funds are moved into the most impactful strategy that has not already reached its limit for assets under management, regardless of which Strategy a user's funds end up in, they receive their portion of yields generated across all Strategies. When a user withdraws, if there are no funds sitting undeployed in the Vault, the Vault withdraws funds from Strategies in the order of least impact. (Funds are taken from the Strategy that will disturb everyone's gains the least, then the next least, etc.) In order to achieve this, the withdrawal queue's order must be properly set and managed by the community (through governance). Vault Strategies are parameterized to pursue the highest risk-adjusted yield. There is an "Emergency Shutdown" mode. When the Vault is put into emergency shutdown, assets will be recalled from the Strategies as quickly as is practical (given on-chain conditions), minimizing loss. Deposits are halted, new Strategies may not be added, and each Strategy exits with the minimum possible damage to position, while opening up deposits to be withdrawn by users. There are no restrictions on withdrawals above what is expected under Normal Operation. For further details, please refer to the specification: https://github.com/iearn-finance/yearn-vaults/blob/main/SPECIFICATION.md

## Functions

### initialize

```
function initialize(address,address,address,string,string)
```

Initializes the Vault, this is called only once, when the contract is deployed. The performance fee is set to 10% of yield, per Strategy. The management fee is set to 2%, per year. The initial deposit limit is set to 0 (deposits disabled); it must be updated after initialization.

If `nameOverride` is not specified, the name will be 'yearn' combined with the name of `token`. If `symbolOverride` is not specified, the symbol will be 'yv' combined with the symbol of `token`. The token used by the vault should not change balances outside transfers and it must transfer the exact amount requested. Fee on transfer and rebasing are not supported.

#### Parameters:

NameTypeDescription* token ** ** The token that may be deposited into this Vault. ** governance ** ** The address authorized for governance interactions. ** rewards ** ** The address to distribute rewards to. ** management ** ** The address of the vault manager. ** nameOverride ** ** Specify a custom Vault name. Leave empty for default choice. ** symbolOverride ** ** Specify a custom Vault symbol name. Leave empty for default choice. ** guardian ** ** The address authorized for guardian interactions. Defaults to caller. *

### initialize

```
function initialize(address,address,address,string,string,address)
```

If `nameOverride` is not specified, the name will be 'yearn' combined with the name of `token`. If `symbolOverride` is not specified, the symbol will be 'yv' combined with the symbol of `token`. The token used by the vault should not change balances outside transfers and it must transfer the exact amount requested. Fee on transfer and rebasing are not supported.

#### Parameters:

NameTypeDescription* token ** ** The token that may be deposited into this Vault. ** governance ** ** The address authorized for governance interactions. ** rewards ** ** The address to distribute rewards to. ** management ** ** The address of the vault manager. ** nameOverride ** ** Specify a custom Vault name. Leave empty for default choice. ** symbolOverride ** ** Specify a custom Vault symbol name. Leave empty for default choice. ** guardian ** ** The address authorized for guardian interactions. Defaults to caller. *

### initialize

```
function initialize(address,address,address,string,string,address,address)
```

If `nameOverride` is not specified, the name will be 'yearn' combined with the name of `token`. If `symbolOverride` is not specified, the symbol will be 'yv' combined with the symbol of `token`. The token used by the vault should not change balances outside transfers and it must transfer the exact amount requested. Fee on transfer and rebasing are not supported.

#### Parameters:

NameTypeDescription* token ** ** The token that may be deposited into this Vault. ** governance ** ** The address authorized for governance interactions. ** rewards ** ** The address to distribute rewards to. ** management ** ** The address of the vault manager. ** nameOverride ** ** Specify a custom Vault name. Leave empty for default choice. ** symbolOverride ** ** Specify a custom Vault symbol name. Leave empty for default choice. ** guardian ** ** The address authorized for guardian interactions. Defaults to caller. *

### apiVersion

```
function apiVersion()
```

Used to track the deployed version of this contract. In practice you can use this version number to compare with Yearn's GitHub and determine which version of the source matches this deployed contract.

All strategies must have an `apiVersion()` that matches the Vault's `API_VERSION`.

#### Return Values:

Description* API_VERSION which holds the current version of this contract. *

### setName

```
function setName(string)
```

Used to change the value of `name`. This may only be called by governance.

#### Parameters:

NameTypeDescription* name ** ** The new name to use. *

### setSymbol

```
function setSymbol(string)
```

Used to change the value of `symbol`. This may only be called by governance.

#### Parameters:

NameTypeDescription* symbol ** ** The new symbol to use. *

### setGovernance

```
function setGovernance(address)
```

Nominate a new address to use as governance. The change does not go into effect immediately. This function sets a pending change, and the governance address is not updated until the proposed governance address has accepted the responsibility. This may only be called by the current governance address.

#### Parameters:

NameTypeDescription* governance ** ** The address requested to take over Vault governance. *

### acceptGovernance

```
function acceptGovernance()
```

Once a new governance address has been proposed using setGovernance(), this function may be called by the proposed address to accept the responsibility of taking over governance for this contract. This may only be called by the proposed governance address.

setGovernance() should be called by the existing governance address, prior to calling this function.

### setManagement

```
function setManagement(address)
```

Changes the management address. Management is able to make some investment decisions adjusting parameters. This may only be called by governance.

#### Parameters:

NameTypeDescription* management ** ** The address to use for managing. *

### setRewards

```
function setRewards(address)
```

Changes the rewards address. Any distributed rewards will cease flowing to the old address and begin flowing to this address once the change is in effect. This will not change any Strategy reports in progress, only new reports made after this change goes into effect. This may only be called by governance.

#### Parameters:

NameTypeDescription* rewards ** ** The address to use for collecting rewards. *

### setLockedProfitDegradation

```
function setLockedProfitDegradation(uint256)
```

Changes the locked profit degradation.

#### Parameters:

NameTypeDescription* degradation ** ** The rate of degradation in percent per second scaled to 1e18. *

### setDepositLimit

```
function setDepositLimit(uint256)
```

Changes the maximum amount of tokens that can be deposited in this Vault. Note, this is not how much may be deposited by a single depositor, but the maximum amount that may be deposited across all depositors. This may only be called by governance.

#### Parameters:

NameTypeDescription* limit ** ** The new deposit limit to use. *

### setPerformanceFee

```
function setPerformanceFee(uint256)
```

Used to change the value of `performanceFee`. Should set this value below the maximum strategist performance fee. This may only be called by governance.

#### Parameters:

NameTypeDescription* fee ** ** The new performance fee to use. *

### setManagementFee

```
function setManagementFee(uint256)
```

Used to change the value of `managementFee`. This may only be called by governance.

#### Parameters:

NameTypeDescription* fee ** ** The new management fee to use. *

### setGuardian

```
function setGuardian(address)
```

Used to change the address of `guardian`. This may only be called by governance or the existing guardian.

#### Parameters:

NameTypeDescription* guardian ** ** The new guardian address to use. *

### setEmergencyShutdown

```
function setEmergencyShutdown(bool)
```

Activates or deactivates Vault mode where all Strategies go into full withdrawal. During Emergency Shutdown: 1. No Users may deposit into the Vault (but may withdraw as usual.) 2. Governance may not add new Strategies. 3. Each Strategy must pay back their debt as quickly as reasonable to minimally affect their position. 4. Only Governance may undo Emergency Shutdown. See contract level note for further details. This may only be called by governance or the guardian.

#### Parameters:

NameTypeDescription* active ** ** If true, the Vault goes into Emergency Shutdown. If false, the Vault goes back into Normal Operation. *

### setWithdrawalQueue

```
function setWithdrawalQueue(address[20])
```

Updates the withdrawalQueue to match the addresses and order specified by `queue`. There can be fewer strategies than the maximum, as well as fewer than the total number of strategies active in the vault. `withdrawalQueue` will be updated in a gas-efficient manner, assuming the input is well- ordered with 0x0 only at the end. This may only be called by governance or management.

This is order sensitive, specify the addresses in the order in which funds should be withdrawn (so `queue`[0] is the first Strategy withdrawn from, `queue`[1] is the second, etc.) This means that the least impactful Strategy (the Strategy that will have its core positions impacted the least by having funds removed) should be at `queue`[0], then the next least impactful at `queue`[1], and so on.

#### Parameters:

NameTypeDescription* queue ** ** The array of addresses to use as the new withdrawal queue. This is order sensitive. *

### transfer

```
function transfer(address,uint256)
```

Transfers shares from the caller's address to `receiver`. This function will always return true, unless the user is attempting to transfer shares to this contract's address, or to 0x0.

#### Parameters:

NameTypeDescription* receiver ** ** The address shares are being transferred to. Must not be this contract's address, must not be 0x0. ** amount ** ** The quantity of shares to transfer. *

#### Return Values:

Description* True if transfer is sent to an address other than this contract's or 0x0, otherwise the transaction will fail. *

### transferFrom

```
function transferFrom(address,address,uint256)
```

Transfers `amount` shares from `sender` to `receiver`. This operation will always return true, unless the user is attempting to transfer shares to this contract's address, or to 0x0. Unless the caller has given this contract unlimited approval, transfering shares will decrement the caller's `allowance` by `amount`.

#### Parameters:

NameTypeDescription* sender ** ** The address shares are being transferred from. ** receiver ** ** The address shares are being transferred to. Must not be this contract's address, must not be 0x0. ** amount ** ** The quantity of shares to transfer. *

#### Return Values:

Description* True if transfer is sent to an address other than this contract's or 0x0, otherwise the transaction will fail. *

### approve

```
function approve(address,uint256)
```

Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729

#### Parameters:

NameTypeDescription* spender ** ** The address which will spend the funds. ** amount ** ** The amount of tokens to be spent. *

### increaseAllowance

```
function increaseAllowance(address,uint256)
```

Increase the allowance of the passed address to spend the total amount of tokens on behalf of msg.sender. This method mitigates the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729

#### Parameters:

NameTypeDescription* spender ** ** The address which will spend the funds. ** amount ** ** The amount of tokens to increase the allowance by. *

### decreaseAllowance

```
function decreaseAllowance(address,uint256)
```

Decrease the allowance of the passed address to spend the total amount of tokens on behalf of msg.sender. This method mitigates the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729

#### Parameters:

NameTypeDescription* spender ** ** The address which will spend the funds. ** amount ** ** The amount of tokens to decrease the allowance by. *

### permit

```
function permit(address,address,uint256,uint256,bytes)
```

Approves spender by owner's signature to expend owner's tokens. See https://eips.ethereum.org/EIPS/eip-2612.

#### Parameters:

NameTypeDescription* owner ** ** The address which is a source of funds and has signed the Permit. ** spender ** ** The address which is allowed to spend the funds. ** amount ** ** The amount of tokens to be spent. ** expiry ** ** The timestamp after which the Permit is no longer valid. ** signature ** ** A valid secp256k1 signature of Permit by owner encoded as r, s, v. *

#### Return Values:

Description* True, if transaction completes successfully *

### totalAssets

```
function totalAssets()
```

Returns the total quantity of all assets under control of this Vault, whether they're loaned out to a Strategy, or currently held in the Vault.

#### Return Values:

Description* The total assets under control of this Vault. *

### deposit

```
function deposit()
```

Deposits `_amount` `token`, issuing shares to `recipient`. If the Vault is in Emergency Shutdown, deposits will not be accepted and this call will fail.

Measuring quantity of shares to issues is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On deposit, this means that shares are issued against the total amount that the deposited capital can be given in service of the debt that Strategies assume. If that number were to be lower than the "expected value" at some future point, depositing shares via this method could entitle the depositor to less than the deposited value once the "realized value" is updated from further reports by the Strategies to the Vaults. Care should be taken by integrators to account for this discrepancy, by using the view-only methods of this contract (both off-chain and on-chain) to determine if depositing into the Vault is a "good idea".

#### Parameters:

NameTypeDescription* _amount ** ** The quantity of tokens to deposit, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. *

#### Return Values:

Description* The issued Vault shares. *

### deposit

```
function deposit(uint256)
```

Measuring quantity of shares to issues is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On deposit, this means that shares are issued against the total amount that the deposited capital can be given in service of the debt that Strategies assume. If that number were to be lower than the "expected value" at some future point, depositing shares via this method could entitle the depositor to less than the deposited value once the "realized value" is updated from further reports by the Strategies to the Vaults. Care should be taken by integrators to account for this discrepancy, by using the view-only methods of this contract (both off-chain and on-chain) to determine if depositing into the Vault is a "good idea".

#### Parameters:

NameTypeDescription* _amount ** ** The quantity of tokens to deposit, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. *

#### Return Values:

Description* The issued Vault shares. *

### deposit

```
function deposit(uint256,address)
```

Measuring quantity of shares to issues is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On deposit, this means that shares are issued against the total amount that the deposited capital can be given in service of the debt that Strategies assume. If that number were to be lower than the "expected value" at some future point, depositing shares via this method could entitle the depositor to less than the deposited value once the "realized value" is updated from further reports by the Strategies to the Vaults. Care should be taken by integrators to account for this discrepancy, by using the view-only methods of this contract (both off-chain and on-chain) to determine if depositing into the Vault is a "good idea".

#### Parameters:

NameTypeDescription* _amount ** ** The quantity of tokens to deposit, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. *

#### Return Values:

Description* The issued Vault shares. *

### maxAvailableShares

```
function maxAvailableShares()
```

Determines the maximum quantity of shares this Vault can facilitate a withdrawal for, factoring in assets currently residing in the Vault, as well as those deployed to strategies on the Vault's balance sheet.

Regarding how shares are calculated, see dev note on `deposit`. If you want to calculated the maximum a user could withdraw up to, you want to use this function. Note that the amount provided by this function is the theoretical maximum possible from withdrawing, the real amount depends on the realized losses incurred during withdrawal.

#### Return Values:

Description* The total quantity of shares this Vault can provide. *

### withdraw

```
function withdraw()
```

Withdraws the calling account's tokens from this Vault, redeeming amount `_shares` for an appropriate amount of tokens. See note on `setWithdrawalQueue` for further details of withdrawal ordering and behavior.

Measuring the value of shares is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On withdrawal, this means that shares are redeemed against the total amount that the deposited capital had "realized" since the point it was deposited, up until the point it was withdrawn. If that number were to be higher than the "expected value" at some future point, withdrawing shares via this method could entitle the depositor to more than the expected value once the "realized value" is updated from further reports by the Strategies to the Vaults. Under exceptional scenarios, this could cause earlier withdrawals to earn "more" of the underlying assets than Users might otherwise be entitled to, if the Vault's estimated value were otherwise measured through external means, accounting for whatever exceptional scenarios exist for the Vault (that aren't covered by the Vault's own design.) In the situation where a large withdrawal happens, it can empty the vault balance and the strategies in the withdrawal queue. Strategies not in the withdrawal queue will have to be harvested to rebalance the funds and make the funds available again to withdraw.

#### Parameters:

NameTypeDescription* maxShares ** ** How many shares to try and redeem for tokens, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. ** maxLoss ** ** The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%. If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal. *

#### Return Values:

Description* The quantity of tokens redeemed for `_shares`. *

### withdraw

```
function withdraw(uint256)
```

Measuring the value of shares is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On withdrawal, this means that shares are redeemed against the total amount that the deposited capital had "realized" since the point it was deposited, up until the point it was withdrawn. If that number were to be higher than the "expected value" at some future point, withdrawing shares via this method could entitle the depositor to more than the expected value once the "realized value" is updated from further reports by the Strategies to the Vaults. Under exceptional scenarios, this could cause earlier withdrawals to earn "more" of the underlying assets than Users might otherwise be entitled to, if the Vault's estimated value were otherwise measured through external means, accounting for whatever exceptional scenarios exist for the Vault (that aren't covered by the Vault's own design.) In the situation where a large withdrawal happens, it can empty the vault balance and the strategies in the withdrawal queue. Strategies not in the withdrawal queue will have to be harvested to rebalance the funds and make the funds available again to withdraw.

#### Parameters:

NameTypeDescription* maxShares ** ** How many shares to try and redeem for tokens, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. ** maxLoss ** ** The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%. If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal. *

#### Return Values:

Description* The quantity of tokens redeemed for `_shares`. *

### withdraw

```
function withdraw(uint256,address)
```

Measuring the value of shares is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On withdrawal, this means that shares are redeemed against the total amount that the deposited capital had "realized" since the point it was deposited, up until the point it was withdrawn. If that number were to be higher than the "expected value" at some future point, withdrawing shares via this method could entitle the depositor to more than the expected value once the "realized value" is updated from further reports by the Strategies to the Vaults. Under exceptional scenarios, this could cause earlier withdrawals to earn "more" of the underlying assets than Users might otherwise be entitled to, if the Vault's estimated value were otherwise measured through external means, accounting for whatever exceptional scenarios exist for the Vault (that aren't covered by the Vault's own design.) In the situation where a large withdrawal happens, it can empty the vault balance and the strategies in the withdrawal queue. Strategies not in the withdrawal queue will have to be harvested to rebalance the funds and make the funds available again to withdraw.

#### Parameters:

NameTypeDescription* maxShares ** ** How many shares to try and redeem for tokens, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. ** maxLoss ** ** The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%. If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal. *

#### Return Values:

Description* The quantity of tokens redeemed for `_shares`. *

### withdraw

```
function withdraw(uint256,address,uint256)
```

Measuring the value of shares is based on the total outstanding debt that this contract has ("expected value") instead of the total balance sheet it has ("estimated value") has important security considerations, and is done intentionally. If this value were measured against external systems, it could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able to claim by redeeming their shares. On withdrawal, this means that shares are redeemed against the total amount that the deposited capital had "realized" since the point it was deposited, up until the point it was withdrawn. If that number were to be higher than the "expected value" at some future point, withdrawing shares via this method could entitle the depositor to more than the expected value once the "realized value" is updated from further reports by the Strategies to the Vaults. Under exceptional scenarios, this could cause earlier withdrawals to earn "more" of the underlying assets than Users might otherwise be entitled to, if the Vault's estimated value were otherwise measured through external means, accounting for whatever exceptional scenarios exist for the Vault (that aren't covered by the Vault's own design.) In the situation where a large withdrawal happens, it can empty the vault balance and the strategies in the withdrawal queue. Strategies not in the withdrawal queue will have to be harvested to rebalance the funds and make the funds available again to withdraw.

#### Parameters:

NameTypeDescription* maxShares ** ** How many shares to try and redeem for tokens, defaults to all. ** recipient ** ** The address to issue the shares in this Vault to. Defaults to the caller's address. ** maxLoss ** ** The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%. If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal. *

#### Return Values:

Description* The quantity of tokens redeemed for `_shares`. *

### pricePerShare

```
function pricePerShare()
```

Gives the price for a single Vault share.

See dev note on `withdraw`.

#### Return Values:

Description* The value of a single share. *

### addStrategy

```
function addStrategy(address,uint256,uint256,uint256,uint256)
```

Add a Strategy to the Vault. This may only be called by governance.

The Strategy will be appended to `withdrawalQueue`, call `setWithdrawalQueue` to change the order.

#### Parameters:

NameTypeDescription* strategy ** ** The address of the Strategy to add. ** debtRatio ** ** The share of the total assets in the `vault that the`strategy` has access to. ** minDebtPerHarvest ** ** Lower limit on the increase of debt since last harvest ** maxDebtPerHarvest ** ** Upper limit on the increase of debt since last harvest ** performanceFee ** ** The fee the strategist will receive based on this Vault's performance. *

### updateStrategyDebtRatio

```
function updateStrategyDebtRatio(address,uint256)
```

Change the quantity of assets `strategy` may manage. This may be called by governance or management.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to update. ** debtRatio ** ** The quantity of assets `strategy` may now manage. *

### updateStrategyMinDebtPerHarvest

```
function updateStrategyMinDebtPerHarvest(address,uint256)
```

Change the quantity assets per block this Vault may deposit to or withdraw from `strategy`. This may only be called by governance or management.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to update. ** minDebtPerHarvest ** ** Lower limit on the increase of debt since last harvest *

### updateStrategyMaxDebtPerHarvest

```
function updateStrategyMaxDebtPerHarvest(address,uint256)
```

Change the quantity assets per block this Vault may deposit to or withdraw from `strategy`. This may only be called by governance or management.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to update. ** maxDebtPerHarvest ** ** Upper limit on the increase of debt since last harvest *

### updateStrategyPerformanceFee

```
function updateStrategyPerformanceFee(address,uint256)
```

Change the fee the strategist will receive based on this Vault's performance. This may only be called by governance.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to update. ** performanceFee ** ** The new fee the strategist will receive. *

### migrateStrategy

```
function migrateStrategy(address,address)
```

Migrates a Strategy, including all assets from `oldVersion` to `newVersion`. This may only be called by governance.

Strategy must successfully migrate all capital and positions to new Strategy, or else this will upset the balance of the Vault. The new Strategy should be "empty" e.g. have no prior commitments to this Vault, otherwise it could have issues.

#### Parameters:

NameTypeDescription* oldVersion ** ** The existing Strategy to migrate from. ** newVersion ** ** The new Strategy to migrate to. *

### revokeStrategy

```
function revokeStrategy()
```

Revoke a Strategy, setting its debt limit to 0 and preventing any future deposits. This function should only be used in the scenario where the Strategy is being retired but no migration of the positions are possible, or in the extreme scenario that the Strategy needs to be put into "Emergency Exit" mode in order for it to exit as quickly as possible. The latter scenario could be for any reason that is considered "critical" that the Strategy exits its position as fast as possible, such as a sudden change in market conditions leading to losses, or an imminent failure in an external dependency. This may only be called by governance, the guardian, or the Strategy itself. Note that a Strategy will only revoke itself during emergency shutdown.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to revoke. *

### revokeStrategy

```
function revokeStrategy(address)
```

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to revoke. *

### addStrategyToQueue

```
function addStrategyToQueue(address)
```

Adds `strategy` to `withdrawalQueue`. This may only be called by governance or management.

The Strategy will be appended to `withdrawalQueue`, call `setWithdrawalQueue` to change the order.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to add. *

### removeStrategyFromQueue

```
function removeStrategyFromQueue(address)
```

Remove `strategy` from `withdrawalQueue`. This may only be called by governance or management.

We don't do this with revokeStrategy because it should still be possible to withdraw from the Strategy if it's unwinding.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to remove. *

### debtOutstanding

```
function debtOutstanding()
```

Determines if `strategy` is past its debt limit and if any tokens should be withdrawn to the Vault.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to check. Defaults to the caller. *

#### Return Values:

Description* The quantity of tokens to withdraw. *

### debtOutstanding

```
function debtOutstanding(address)
```

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to check. Defaults to the caller. *

#### Return Values:

Description* The quantity of tokens to withdraw. *

### creditAvailable

```
function creditAvailable()
```

Amount of tokens in Vault a Strategy has access to as a credit line. This will check the Strategy's debt limit, as well as the tokens available in the Vault, and determine the maximum amount of tokens (if any) the Strategy may draw on. In the rare case the Vault is in emergency shutdown this will return 0.

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to check. Defaults to caller. *

#### Return Values:

Description* The quantity of tokens available for the Strategy to draw on. *

### creditAvailable

```
function creditAvailable(address)
```

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to check. Defaults to caller. *

#### Return Values:

Description* The quantity of tokens available for the Strategy to draw on. *

### expectedReturn

```
function expectedReturn()
```

Provide an accurate expected value for the return this `strategy` would provide to the Vault the next time `report()` is called (since the last time it was called).

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to determine the expected return for. Defaults to caller. *

#### Return Values:

Description* The anticipated amount `strategy` should make on its investment since its last report. *

### expectedReturn

```
function expectedReturn(address)
```

#### Parameters:

NameTypeDescription* strategy ** ** The Strategy to determine the expected return for. Defaults to caller. *

#### Return Values:

Description* The anticipated amount `strategy` should make on its investment since its last report. *

### report

```
function report(uint256,uint256,uint256)
```

Reports the amount of assets the calling Strategy has free (usually in terms of ROI). The performance fee is determined here, off of the strategy's profits (if any), and sent to governance. The strategist's fee is also determined here (off of profits), to be handled according to the strategist on the next harvest. This may only be called by a Strategy managed by this Vault.

For approved strategies, this is the most efficient behavior. The Strategy reports back what it has free, then Vault "decides" whether to take some back or give it more. Note that the most it can take is `gain + _debtPayment`, and the most it can give is all of the remaining reserves. Anything outside of those bounds is abnormal behavior. All approved strategies must have increased diligence around calling this function, as abnormal behavior could become catastrophic.

#### Parameters:

NameTypeDescription* gain ** ** Amount Strategy has realized as a gain on it's investment since its last report, and is free to be given back to Vault as earnings ** loss ** ** Amount Strategy has realized as a loss on it's investment since its last report, and should be accounted for on the Vault's balance sheet. The loss will reduce the debtRatio. The next time the strategy will harvest, it will pay back the debt in an attempt to adjust to the new debt limit. ** _debtPayment ** ** Amount Strategy has made available to cover outstanding debt *

#### Return Values:

Description* Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown). *

### sweep

```
function sweep(address)
```

Removes tokens from this Vault that are not the type of token managed by this Vault. This may be used in case of accidentally sending the wrong kind of token to this Vault. Tokens will be sent to `governance`. This will fail if an attempt is made to sweep the tokens that this Vault manages. This may only be called by governance.

#### Parameters:

NameTypeDescription* token ** ** The token to transfer out of this vault. ** amount ** ** The quantity or tokenId to transfer out. *

### sweep

```
function sweep(address,uint256)
```

#### Parameters:

NameTypeDescription* token ** ** The token to transfer out of this vault. ** amount ** ** The quantity or tokenId to transfer out. *

## Events

Transfer

- `sender` : address, indexed

- `receiver` : address, indexed

- `value` : uint256, notIndexed

Approval

- `owner` : address, indexed

- `spender` : address, indexed

- `value` : uint256, notIndexed

Deposit

- `recipient` : address, indexed

- `shares` : uint256, notIndexed

- `amount` : uint256, notIndexed

Withdraw

- `recipient` : address, indexed

- `shares` : uint256, notIndexed

- `amount` : uint256, notIndexed

Sweep

- `token` : address, indexed

- `amount` : uint256, notIndexed

LockedProfitDegradationUpdated

- `value` : uint256, notIndexed

StrategyAdded

- `strategy` : address, indexed

- `debtRatio` : uint256, notIndexed

- `minDebtPerHarvest` : uint256, notIndexed

- `maxDebtPerHarvest` : uint256, notIndexed

- `performanceFee` : uint256, notIndexed

StrategyReported

- `strategy` : address, indexed

- `gain` : uint256, notIndexed

- `loss` : uint256, notIndexed

- `debtPaid` : uint256, notIndexed

- `totalGain` : uint256, notIndexed

- `totalLoss` : uint256, notIndexed

- `totalDebt` : uint256, notIndexed

- `debtAdded` : uint256, notIndexed

- `debtRatio` : uint256, notIndexed

FeeReport

- `management_fee` : uint256, notIndexed

- `performance_fee` : uint256, notIndexed

- `strategist_fee` : uint256, notIndexed

- `duration` : uint256, notIndexed

WithdrawFromStrategy

- `strategy` : address, indexed

- `totalDebt` : uint256, notIndexed

- `loss` : uint256, notIndexed

UpdateGovernance

- `governance` : address, notIndexed

UpdateManagement

- `management` : address, notIndexed

UpdateRewards

- `rewards` : address, notIndexed

UpdateDepositLimit

- `depositLimit` : uint256, notIndexed

UpdatePerformanceFee

- `performanceFee` : uint256, notIndexed

UpdateManagementFee

- `managementFee` : uint256, notIndexed

UpdateGuardian

- `guardian` : address, notIndexed

EmergencyShutdown

- `active` : bool, notIndexed

UpdateWithdrawalQueue

- `queue` : address[20], notIndexed

StrategyUpdateDebtRatio

- `strategy` : address, indexed

- `debtRatio` : uint256, notIndexed

StrategyUpdateMinDebtPerHarvest

- `strategy` : address, indexed

- `minDebtPerHarvest` : uint256, notIndexed

StrategyUpdateMaxDebtPerHarvest

- `strategy` : address, indexed

- `maxDebtPerHarvest` : uint256, notIndexed

StrategyUpdatePerformanceFee

- `strategy` : address, indexed

- `performanceFee` : uint256, notIndexed

StrategyMigrated

- `oldVersion` : address, indexed

- `newVersion` : address, indexed

StrategyRevoked

- `strategy` : address, indexed

StrategyRemovedFromQueue

- `strategy` : address, indexed

StrategyAddedToQueue

- `strategy` : address, indexed

NewPendingGovernance

- `pendingGovernance` : address, indexed


StrategyAPI

StrategyAPI

Functions

name

vault

want

apiVersion

keeper

isActive

delegatedAssets

estimatedTotalAssets

tendTrigger

tend

harvestTrigger

harvest

Events

Harvested

# StrategyAPI

This interface is here for the keeper bot to use.

## Functions

### name

```
function name( ) external returns (string)
```

### vault

```
function vault( ) external returns (address)
```

### want

```
function want( ) external returns (address)
```

### apiVersion

```
function apiVersion( ) external returns (string)
```

### keeper

```
function keeper( ) external returns (address)
```

### isActive

```
function isActive( ) external returns (bool)
```

### delegatedAssets

```
function delegatedAssets( ) external returns (uint256)
```

### estimatedTotalAssets

```
function estimatedTotalAssets( ) external returns (uint256)
```

### tendTrigger

```
function tendTrigger( ) external returns (bool)
```

### tend

```
function tend( ) external
```

### harvestTrigger

```
function harvestTrigger( ) external returns (bool)
```

### harvest

```
function harvest( ) external
```

## Events

### Harvested

```
event Harvested( )
```