Transaction Hash:
Block:
13517114 at Oct-30-2021 07:21:28 AM +UTC
Transaction Fee:
0.01793743655422546 ETH
$56.98
Gas Used:
142,364 Gas / 125.996997515 Gwei
Emitted Events:
| 36 |
Vyper_contract.Approval( owner=[Sender] 0x0d900f82b517db9f1cb06676733bb54c77014635, spender=[Receiver] yVault_ZapOut_V3_0_1, value=0 )
|
| 37 |
Vyper_contract.Transfer( sender=[Sender] 0x0d900f82b517db9f1cb06676733bb54c77014635, receiver=[Receiver] yVault_ZapOut_V3_0_1, value=2685756114515271309 )
|
| 38 |
Vyper_contract.Transfer( sender=[Receiver] yVault_ZapOut_V3_0_1, receiver=0x0000000000000000000000000000000000000000, value=2685756114515271309 )
|
| 39 |
WETH9.Transfer( src=Vyper_contract, dst=[Receiver] yVault_ZapOut_V3_0_1, wad=2702216535786058471 )
|
| 40 |
WETH9.Withdrawal( src=[Receiver] yVault_ZapOut_V3_0_1, wad=2702216535786058471 )
|
| 41 |
yVault_ZapOut_V3_0_1.zapOut( sender=[Sender] 0x0d900f82b517db9f1cb06676733bb54c77014635, pool=Vyper_contract, token=0x0000000000000000000000000000000000000000, tokensRec=2702216535786058471 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x0D900f82...C77014635 |
0.093541928670261577 Eth
Nonce: 4685
|
2.777821027902094588 Eth
Nonce: 4686
| 2.684279099231833011 | ||
|
0x52bc44d5...b7d7bE3b5
Miner
| (Nanopool) | 3,685.994398480785152061 Eth | 3,685.994718799785152061 Eth | 0.000320319 | |
| 0xa258C460...b854D168c | |||||
| 0xC02aaA39...83C756Cc2 | 7,449,066.625747403455465053 Eth | 7,449,063.923530867669406582 Eth | 2.702216535786058471 |
Execution Trace
yVault_ZapOut_V3_0_1.ZapOut( fromVault=0xa258C4606Ca8206D8aA700cE2143D7db854D168c, amountIn=2685756114515271309, toToken=0x0000000000000000000000000000000000000000, isAaveUnderlying=False, minToTokens=2676935662198176559, swapTarget=0x0000000000000000000000000000000000000000, swapData=0x00, affiliate=0xFEB4acf3df3cDEA7399794D0869ef76A6EfAff52, shouldSellEntireBalance=False ) => ( tokensReceived=2702216535786058471 )
Vyper_contract.transferFrom( sender=0x0D900f82b517db9F1cB06676733bB54C77014635, receiver=0xd6b88257e91e4E4D4E990B3A858c849EF2DFdE8c, amount=2685756114515271309 ) => ( True )
-
Vyper_contract.transferFrom( sender=0x0D900f82b517db9F1cB06676733bB54C77014635, receiver=0xd6b88257e91e4E4D4E990B3A858c849EF2DFdE8c, amount=2685756114515271309 ) => ( True )
-
Vyper_contract.STATICCALL( )
-
Vyper_contract.DELEGATECALL( )
-
-
WETH9.balanceOf( 0xd6b88257e91e4E4D4E990B3A858c849EF2DFdE8c ) => ( 0 )
Vyper_contract.withdraw( maxShares=2685756114515271309 ) => ( 2702216535786058471 )
Vyper_contract.withdraw( maxShares=2685756114515271309 ) => ( 2702216535786058471 )
-
WETH9.balanceOf( 0xa258C4606Ca8206D8aA700cE2143D7db854D168c ) => ( 86830554002718231372659 )
-
WETH9.balanceOf( 0xa258C4606Ca8206D8aA700cE2143D7db854D168c ) => ( 86830554002718231372659 )
-
Null: 0x000...004.CALL( )
-
Null: 0x000...004.00000000( )
-
WETH9.transfer( dst=0xd6b88257e91e4E4D4E990B3A858c849EF2DFdE8c, wad=2702216535786058471 ) => ( True )
-
Null: 0x000...004.00000000( )
-
-
WETH9.balanceOf( 0xd6b88257e91e4E4D4E990B3A858c849EF2DFdE8c ) => ( 2702216535786058471 )
WETH9.withdraw( wad=2702216535786058471 )
- ETH 2.702216535786058471
yVault_ZapOut_V3_0_1.CALL( )
- ETH 2.702216535786058471
- ETH 2.702216535786058471
0x0d900f82b517db9f1cb06676733bb54c77014635.CALL( )
ZapOut[yVault_ZapOut_V3_0_1 (ln:864)]
_pullTokens[yVault_ZapOut_V3_0_1 (ln:875)]token[yVault_ZapOut_V3_0_1 (ln:877)]_vaultWithdraw[yVault_ZapOut_V3_0_1 (ln:879)]_getBalance[yVault_ZapOut_V3_0_1 (ln:925)]withdraw[yVault_ZapOut_V3_0_1 (ln:926)]_getBalance[yVault_ZapOut_V3_0_1 (ln:928)]
underlyingAssetAddress[yVault_ZapOut_V3_0_1 (ln:884)]redeem[yVault_ZapOut_V3_0_1 (ln:886)]_fillQuote[yVault_ZapOut_V3_0_1 (ln:891)]withdraw[yVault_ZapOut_V3_0_1 (ln:942)]_approveToken[yVault_ZapOut_V3_0_1 (ln:949)]_getBalance[yVault_ZapOut_V3_0_1 (ln:951)]call[yVault_ZapOut_V3_0_1 (ln:953)]_getBalance[yVault_ZapOut_V3_0_1 (ln:955)]
_fillQuote[yVault_ZapOut_V3_0_1 (ln:900)]withdraw[yVault_ZapOut_V3_0_1 (ln:942)]_approveToken[yVault_ZapOut_V3_0_1 (ln:949)]_getBalance[yVault_ZapOut_V3_0_1 (ln:951)]call[yVault_ZapOut_V3_0_1 (ln:953)]_getBalance[yVault_ZapOut_V3_0_1 (ln:955)]
_subtractGoodwill[yVault_ZapOut_V3_0_1 (ln:910)]sendValue[yVault_ZapOut_V3_0_1 (ln:914)]payable[yVault_ZapOut_V3_0_1 (ln:914)]safeTransfer[yVault_ZapOut_V3_0_1 (ln:916)]zapOut[yVault_ZapOut_V3_0_1 (ln:918)]
File 1 of 4: yVault_ZapOut_V3_0_1
File 2 of 4: Vyper_contract
File 3 of 4: WETH9
File 4 of 4: Vyper_contract
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.0;
import "../oz/0.8.0/access/Ownable.sol";
import "../oz/0.8.0/token/ERC20/utils/SafeERC20.sol";
abstract contract ZapBaseV2 is Ownable {
using SafeERC20 for IERC20;
bool public stopped = false;
// if true, goodwill is not deducted
mapping(address => bool) public feeWhitelist;
uint256 public goodwill;
// % share of goodwill (0-100 %)
uint256 affiliateSplit;
// restrict affiliates
mapping(address => bool) public affiliates;
// affiliate => token => amount
mapping(address => mapping(address => uint256)) public affiliateBalance;
// token => amount
mapping(address => uint256) public totalAffiliateBalance;
// swapTarget => approval status
mapping(address => bool) public approvedTargets;
address internal constant ETHAddress =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(uint256 _goodwill, uint256 _affiliateSplit) {
goodwill = _goodwill;
affiliateSplit = _affiliateSplit;
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
function _getBalance(address token)
internal
view
returns (uint256 balance)
{
if (token == address(0)) {
balance = address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
function _approveToken(address token, address spender) internal {
IERC20 _token = IERC20(token);
if (_token.allowance(address(this), spender) > 0) return;
else {
_token.safeApprove(spender, type(uint256).max);
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20(token).safeApprove(spender, 0);
IERC20(token).safeApprove(spender, amount);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
function set_feeWhitelist(address zapAddress, bool status)
external
onlyOwner
{
feeWhitelist[zapAddress] = status;
}
function set_new_goodwill(uint256 _new_goodwill) public onlyOwner {
require(
_new_goodwill >= 0 && _new_goodwill <= 100,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
function set_new_affiliateSplit(uint256 _new_affiliateSplit)
external
onlyOwner
{
require(
_new_affiliateSplit <= 100,
"Affiliate Split Value not allowed"
);
affiliateSplit = _new_affiliateSplit;
}
function set_affiliate(address _affiliate, bool _status)
external
onlyOwner
{
affiliates[_affiliate] = _status;
}
///@notice Withdraw goodwill share, retaining affilliate share
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty = address(this).balance - totalAffiliateBalance[tokens[i]];
Address.sendValue(payable(owner()), qty);
} else {
qty =
IERC20(tokens[i]).balanceOf(address(this)) -
totalAffiliateBalance[tokens[i]];
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
///@notice Withdraw affilliate share, retaining goodwill share
function affilliateWithdraw(address[] calldata tokens) external {
uint256 tokenBal;
for (uint256 i = 0; i < tokens.length; i++) {
tokenBal = affiliateBalance[msg.sender][tokens[i]];
affiliateBalance[msg.sender][tokens[i]] = 0;
totalAffiliateBalance[tokens[i]] =
totalAffiliateBalance[tokens[i]] -
tokenBal;
if (tokens[i] == ETHAddress) {
Address.sendValue(payable(msg.sender), tokenBal);
} else {
IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal);
}
}
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
receive() external payable {
require(msg.sender != tx.origin, "Do not send ETH directly");
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.0;
import "./ZapBaseV2.sol";
abstract contract ZapOutBaseV3 is ZapBaseV2 {
using SafeERC20 for IERC20;
/**
@dev Transfer tokens from msg.sender to this contract
@param token The ERC20 token to transfer to this contract
@param shouldSellEntireBalance If True transfers entrire allowable amount from another contract
@return Quantity of tokens transferred to this contract
*/
function _pullTokens(
address token,
uint256 amount,
bool shouldSellEntireBalance
) internal returns (uint256) {
if (shouldSellEntireBalance) {
require(
Address.isContract(msg.sender),
"ERR: shouldSellEntireBalance is true for EOA"
);
uint256 allowance =
IERC20(token).allowance(msg.sender, address(this));
IERC20(token).safeTransferFrom(
msg.sender,
address(this),
allowance
);
return allowance;
} else {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
return amount;
}
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill && !whitelisted && goodwill > 0) {
totalGoodwillPortion = (amount * goodwill) / 10000;
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
(totalGoodwillPortion * affiliateSplit) / 100;
affiliateBalance[affiliate][token] += affiliatePortion;
totalAffiliateBalance[token] += affiliatePortion;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(
oldAllowance >= value,
"SafeERC20: decreased allowance below zero"
);
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
///@author Zapper
///@notice This contract removes liquidity from yEarn Vaults to ETH or ERC20 Tokens.
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.0;
import "../_base/ZapOutBaseV3.sol";
interface IWETH {
function withdraw(uint256 wad) external;
}
interface IYVault {
function deposit(uint256) external;
function withdraw(uint256) external;
function getPricePerFullShare() external view returns (uint256);
function token() external view returns (address);
function decimals() external view returns (uint256);
// V2
function pricePerShare() external view returns (uint256);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
function name() external pure returns (string memory);
function nonces(address owner) external view returns (uint256);
}
interface IYVaultV1Registry {
function getVaults() external view returns (address[] memory);
function getVaultsLength() external view returns (uint256);
}
// -- Aave --
interface IAToken {
function redeem(uint256 _amount) external;
function underlyingAssetAddress() external returns (address);
}
contract yVault_ZapOut_V3_0_1 is ZapOutBaseV3 {
using SafeERC20 for IERC20;
IYVaultV1Registry V1Registry =
IYVaultV1Registry(0x3eE41C098f9666ed2eA246f4D2558010e59d63A0);
address private constant wethTokenAddress =
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 private constant deadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
uint256 private constant permitAllowance = 79228162514260000000000000000;
event zapOut(
address sender,
address pool,
address token,
uint256 tokensRec
);
constructor(
address _curveZapOut,
uint256 _goodwill,
uint256 _affiliateSplit
) ZapBaseV2(_goodwill, _affiliateSplit) {
// Curve ZapOut
approvedTargets[_curveZapOut] = true;
// 0x exchange
approvedTargets[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
}
/**
@notice Zap out in to a single token with permit
@param fromVault Vault from which to remove liquidity
@param amountIn Quantity of vault tokens to remove
@param toToken Address of desired token
@param isAaveUnderlying True if vault contains aave token
@param minToTokens Minimum quantity of tokens to receive, reverts otherwise
@param permitSig Encoded permit hash, which contains r,s,v values
@param swapTarget Execution targets for swap or Zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@param shouldSellEntireBalance If True transfers entrire allowable amount from another contract
@return tokensReceived Quantity of tokens or ETH received
*/
function ZapOutWithPermit(
address fromVault,
uint256 amountIn,
address toToken,
bool isAaveUnderlying,
uint256 minToTokens,
bytes calldata permitSig,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external returns (uint256 tokensReceived) {
// permit
_permit(fromVault, permitAllowance, permitSig);
return
ZapOut(
fromVault,
amountIn,
toToken,
isAaveUnderlying,
minToTokens,
swapTarget,
swapData,
affiliate,
shouldSellEntireBalance
);
}
function _permit(
address fromVault,
uint256 amountIn,
bytes memory permitSig
) internal {
bool success =
IYVault(fromVault).permit(
msg.sender,
address(this),
amountIn,
deadline,
permitSig
);
require(success, "Could Not Permit");
}
/**
@notice Zap out in to a single token with permit
@param fromVault Vault from which to remove liquidity
@param amountIn Quantity of vault tokens to remove
@param toToken Address of desired token
@param isAaveUnderlying True if vault contains aave token
@param minToTokens Minimum quantity of tokens to receive, reverts otherwise
@param swapTarget Execution targets for swap or Zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@param shouldSellEntireBalance If True transfers entrire allowable amount from another contract
@return tokensReceived Quantity of tokens or ETH received
*/
function ZapOut(
address fromVault,
uint256 amountIn,
address toToken,
bool isAaveUnderlying,
uint256 minToTokens,
address swapTarget,
bytes memory swapData,
address affiliate,
bool shouldSellEntireBalance
) public stopInEmergency returns (uint256 tokensReceived) {
_pullTokens(fromVault, amountIn, shouldSellEntireBalance);
// get underlying token from vault
address underlyingToken = IYVault(fromVault).token();
uint256 underlyingTokenReceived =
_vaultWithdraw(fromVault, amountIn, underlyingToken);
// swap to toToken
uint256 toTokenAmt;
if (isAaveUnderlying) {
address underlyingAsset =
IAToken(underlyingToken).underlyingAssetAddress();
// unwrap atoken
IAToken(underlyingToken).redeem(underlyingTokenReceived);
// aTokens are 1:1
if (underlyingAsset == toToken) {
toTokenAmt = underlyingTokenReceived;
} else {
toTokenAmt = _fillQuote(
underlyingAsset,
toToken,
underlyingTokenReceived,
swapTarget,
swapData
);
}
} else {
toTokenAmt = _fillQuote(
underlyingToken,
toToken,
underlyingTokenReceived,
swapTarget,
swapData
);
}
require(toTokenAmt >= minToTokens, "Err: High Slippage");
uint256 totalGoodwillPortion =
_subtractGoodwill(toToken, toTokenAmt, affiliate, true);
tokensReceived = toTokenAmt - totalGoodwillPortion;
// send toTokens
if (toToken == address(0)) {
Address.sendValue(payable(msg.sender), tokensReceived);
} else {
IERC20(toToken).safeTransfer(msg.sender, tokensReceived);
}
emit zapOut(msg.sender, fromVault, toToken, tokensReceived);
}
function _vaultWithdraw(
address fromVault,
uint256 amount,
address underlyingVaultToken
) internal returns (uint256 underlyingReceived) {
uint256 iniUnderlyingBal = _getBalance(underlyingVaultToken);
IYVault(fromVault).withdraw(amount);
underlyingReceived =
_getBalance(underlyingVaultToken) -
iniUnderlyingBal;
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapData
) internal returns (uint256 amtBought) {
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == wethTokenAddress && toToken == address(0)) {
IWETH(wethTokenAddress).withdraw(_amount);
return _amount;
}
uint256 valueToSend;
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget, _amount);
}
uint256 iniBal = _getBalance(toToken);
require(approvedTargets[_swapTarget], "Target not Authorized");
(bool success, ) = _swapTarget.call{ value: valueToSend }(swapData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
require(finalBal > 0, "ERR: Swapped to wrong token");
amtBought = finalBal - iniBal;
}
/**
@notice Utility function to determine the quantity of underlying tokens removed from vault
@param fromVault Yearn vault from which to remove liquidity
@param liquidity Quantity of vault tokens to remove
@return Quantity of underlying LP or token removed
*/
function removeLiquidityReturn(address fromVault, uint256 liquidity)
external
view
returns (uint256)
{
IYVault vault = IYVault(fromVault);
address[] memory V1Vaults = V1Registry.getVaults();
for (uint256 i = 0; i < V1Registry.getVaultsLength(); i++) {
if (V1Vaults[i] == fromVault)
return (liquidity * (vault.getPricePerFullShare())) / (10**18);
}
return (liquidity * (vault.pricePerShare())) / (10**vault.decimals());
}
}
File 2 of 4: Vyper_contract
# @version 0.2.12
"""
@title Yearn Token Vault
@license GNU AGPLv3
@author yearn.finance
@notice
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/master/SPECIFICATION.md
"""
API_VERSION: constant(String[28]) = "0.4.2"
from vyper.interfaces import ERC20
implements: ERC20
interface DetailedERC20:
def name() -> String[42]: view
def symbol() -> String[20]: view
def decimals() -> uint256: view
interface Strategy:
def want() -> address: view
def vault() -> address: view
def isActive() -> bool: view
def delegatedAssets() -> uint256: view
def estimatedTotalAssets() -> uint256: view
def withdraw(_amount: uint256) -> uint256: nonpayable
def migrate(_newStrategy: address): nonpayable
event Transfer:
sender: indexed(address)
receiver: indexed(address)
value: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
value: uint256
name: public(String[64])
symbol: public(String[32])
decimals: public(uint256)
balanceOf: public(HashMap[address, uint256])
allowance: public(HashMap[address, HashMap[address, uint256]])
totalSupply: public(uint256)
token: public(ERC20)
governance: public(address)
management: public(address)
guardian: public(address)
pendingGovernance: address
struct StrategyParams:
performanceFee: uint256 # Strategist's fee (basis points)
activation: uint256 # Activation block.timestamp
debtRatio: uint256 # Maximum borrow amount (in BPS of total assets)
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
lastReport: uint256 # block.timestamp of the last time a report occured
totalDebt: uint256 # Total outstanding debt that Strategy has
totalGain: uint256 # Total returns that Strategy has realized for Vault
totalLoss: uint256 # Total losses that Strategy has realized for Vault
event StrategyAdded:
strategy: indexed(address)
debtRatio: uint256 # Maximum borrow amount (in BPS of total assets)
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
performanceFee: uint256 # Strategist's fee (basis points)
event StrategyReported:
strategy: indexed(address)
gain: uint256
loss: uint256
debtPaid: uint256
totalGain: uint256
totalLoss: uint256
totalDebt: uint256
debtAdded: uint256
debtRatio: uint256
event UpdateGovernance:
governance: address # New active governance
event UpdateManagement:
management: address # New active manager
event UpdateRewards:
rewards: address # New active rewards recipient
event UpdateDepositLimit:
depositLimit: uint256 # New active deposit limit
event UpdatePerformanceFee:
performanceFee: uint256 # New active performance fee
event UpdateManagementFee:
managementFee: uint256 # New active management fee
event UpdateGuardian:
guardian: address # Address of the active guardian
event EmergencyShutdown:
active: bool # New emergency shutdown state (if false, normal operation enabled)
event UpdateWithdrawalQueue:
queue: address[MAXIMUM_STRATEGIES] # New active withdrawal queue
event StrategyUpdateDebtRatio:
strategy: indexed(address) # Address of the strategy for the debt ratio adjustment
debtRatio: uint256 # The new debt limit for the strategy (in BPS of total assets)
event StrategyUpdateMinDebtPerHarvest:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
event StrategyUpdateMaxDebtPerHarvest:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
event StrategyUpdatePerformanceFee:
strategy: indexed(address) # Address of the strategy for the performance fee adjustment
performanceFee: uint256 # The new performance fee for the strategy
event StrategyMigrated:
oldVersion: indexed(address) # Old version of the strategy to be migrated
newVersion: indexed(address) # New version of the strategy
event StrategyRevoked:
strategy: indexed(address) # Address of the strategy that is revoked
event StrategyRemovedFromQueue:
strategy: indexed(address) # Address of the strategy that is removed from the withdrawal queue
event StrategyAddedToQueue:
strategy: indexed(address) # Address of the strategy that is added to the withdrawal queue
# NOTE: Track the total for overhead targeting purposes
strategies: public(HashMap[address, StrategyParams])
MAXIMUM_STRATEGIES: constant(uint256) = 20
DEGRADATION_COEFFICIENT: constant(uint256) = 10 ** 18
# Ordering that `withdraw` uses to determine which strategies to pull funds from
# NOTE: Does *NOT* have to match the ordering of all the current strategies that
# exist, but it is recommended that it does or else withdrawal depth is
# limited to only those inside the queue.
# NOTE: Ordering is determined by governance, and should be balanced according
# to risk, slippage, and/or volatility. Can also be ordered to increase the
# withdrawal speed of a particular Strategy.
# NOTE: The first time a ZERO_ADDRESS is encountered, it stops withdrawing
withdrawalQueue: public(address[MAXIMUM_STRATEGIES])
emergencyShutdown: public(bool)
depositLimit: public(uint256) # Limit for totalAssets the Vault can hold
debtRatio: public(uint256) # Debt ratio for the Vault across all strategies (in BPS, <= 10k)
totalDebt: public(uint256) # Amount of tokens that all strategies have borrowed
lastReport: public(uint256) # block.timestamp of last report
activation: public(uint256) # block.timestamp of contract deployment
lockedProfit: public(uint256) # how much profit is locked and cant be withdrawn
lockedProfitDegradation: public(uint256) # rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block
rewards: public(address) # Rewards contract where Governance fees are sent to
# Governance Fee for management of Vault (given to `rewards`)
managementFee: public(uint256)
# Governance Fee for performance of Vault (given to `rewards`)
performanceFee: public(uint256)
MAX_BPS: constant(uint256) = 10_000 # 100%, or 10k basis points
# NOTE: A four-century period will be missing 3 of its 100 Julian leap years, leaving 97.
# So the average year has 365 + 97/400 = 365.2425 days
# ERROR(Julian): -0.0078
# ERROR(Gregorian): -0.0003
SECS_PER_YEAR: constant(uint256) = 31_556_952 # 365.2425 days
# `nonces` track `permit` approvals with signature.
nonces: public(HashMap[address, uint256])
DOMAIN_SEPARATOR: public(bytes32)
DOMAIN_TYPE_HASH: constant(bytes32) = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
PERMIT_TYPE_HASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
@external
def initialize(
token: address,
governance: address,
rewards: address,
nameOverride: String[64],
symbolOverride: String[32],
guardian: address = msg.sender,
management: address = msg.sender,
):
"""
@notice
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.
@dev
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.
@param token The token that may be deposited into this Vault.
@param governance The address authorized for governance interactions.
@param rewards The address to distribute rewards to.
@param management The address of the vault manager.
@param nameOverride Specify a custom Vault name. Leave empty for default choice.
@param symbolOverride Specify a custom Vault symbol name. Leave empty for default choice.
@param guardian The address authorized for guardian interactions. Defaults to caller.
"""
assert self.activation == 0 # dev: no devops199
self.token = ERC20(token)
if nameOverride == "":
self.name = concat(DetailedERC20(token).symbol(), " yVault")
else:
self.name = nameOverride
if symbolOverride == "":
self.symbol = concat("yv", DetailedERC20(token).symbol())
else:
self.symbol = symbolOverride
decimals: uint256 = DetailedERC20(token).decimals()
self.decimals = decimals
assert decimals < 256 # dev: see VVE-2020-0001
self.governance = governance
log UpdateGovernance(governance)
self.management = management
log UpdateManagement(management)
self.rewards = rewards
log UpdateRewards(rewards)
self.guardian = guardian
log UpdateGuardian(guardian)
self.performanceFee = 1000 # 10% of yield (per Strategy)
log UpdatePerformanceFee(convert(1000, uint256))
self.managementFee = 200 # 2% per year
log UpdateManagementFee(convert(200, uint256))
self.lastReport = block.timestamp
self.activation = block.timestamp
self.lockedProfitDegradation = convert(DEGRADATION_COEFFICIENT * 46 / 10 ** 6 , uint256) # 6 hours in blocks
# EIP-712
self.DOMAIN_SEPARATOR = keccak256(
concat(
DOMAIN_TYPE_HASH,
keccak256(convert("Yearn Vault", Bytes[11])),
keccak256(convert(API_VERSION, Bytes[28])),
convert(chain.id, bytes32),
convert(self, bytes32)
)
)
@pure
@external
def apiVersion() -> String[28]:
"""
@notice
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.
@dev
All strategies must have an `apiVersion()` that matches the Vault's
`API_VERSION`.
@return API_VERSION which holds the current version of this contract.
"""
return API_VERSION
@external
def setName(name: String[42]):
"""
@notice
Used to change the value of `name`.
This may only be called by governance.
@param name The new name to use.
"""
assert msg.sender == self.governance
self.name = name
@external
def setSymbol(symbol: String[20]):
"""
@notice
Used to change the value of `symbol`.
This may only be called by governance.
@param symbol The new symbol to use.
"""
assert msg.sender == self.governance
self.symbol = symbol
# 2-phase commit for a change in governance
@external
def setGovernance(governance: address):
"""
@notice
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.
@param governance The address requested to take over Vault governance.
"""
assert msg.sender == self.governance
self.pendingGovernance = governance
@external
def acceptGovernance():
"""
@notice
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.
@dev
setGovernance() should be called by the existing governance address,
prior to calling this function.
"""
assert msg.sender == self.pendingGovernance
self.governance = msg.sender
log UpdateGovernance(msg.sender)
@external
def setManagement(management: address):
"""
@notice
Changes the management address.
Management is able to make some investment decisions adjusting parameters.
This may only be called by governance.
@param management The address to use for managing.
"""
assert msg.sender == self.governance
self.management = management
log UpdateManagement(management)
@external
def setRewards(rewards: address):
"""
@notice
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.
@param rewards The address to use for collecting rewards.
"""
assert msg.sender == self.governance
assert not (rewards in [self, ZERO_ADDRESS])
self.rewards = rewards
log UpdateRewards(rewards)
@external
def setLockedProfitDegradation(degradation: uint256):
"""
@notice
Changes the locked profit degradation.
@param degradation The rate of degradation in percent per second scaled to 1e18.
"""
assert msg.sender == self.governance
# Since "degradation" is of type uint256 it can never be less than zero
assert degradation <= DEGRADATION_COEFFICIENT
self.lockedProfitDegradation = degradation
@external
def setDepositLimit(limit: uint256):
"""
@notice
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.
@param limit The new deposit limit to use.
"""
assert msg.sender == self.governance
self.depositLimit = limit
log UpdateDepositLimit(limit)
@external
def setPerformanceFee(fee: uint256):
"""
@notice
Used to change the value of `performanceFee`.
Should set this value below the maximum strategist performance fee.
This may only be called by governance.
@param fee The new performance fee to use.
"""
assert msg.sender == self.governance
assert fee <= MAX_BPS / 2
self.performanceFee = fee
log UpdatePerformanceFee(fee)
@external
def setManagementFee(fee: uint256):
"""
@notice
Used to change the value of `managementFee`.
This may only be called by governance.
@param fee The new management fee to use.
"""
assert msg.sender == self.governance
assert fee <= MAX_BPS
self.managementFee = fee
log UpdateManagementFee(fee)
@external
def setGuardian(guardian: address):
"""
@notice
Used to change the address of `guardian`.
This may only be called by governance or the existing guardian.
@param guardian The new guardian address to use.
"""
assert msg.sender in [self.guardian, self.governance]
self.guardian = guardian
log UpdateGuardian(guardian)
@external
def setEmergencyShutdown(active: bool):
"""
@notice
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.
@param active
If true, the Vault goes into Emergency Shutdown. If false, the Vault
goes back into Normal Operation.
"""
if active:
assert msg.sender in [self.guardian, self.governance]
else:
assert msg.sender == self.governance
self.emergencyShutdown = active
log EmergencyShutdown(active)
@external
def setWithdrawalQueue(queue: address[MAXIMUM_STRATEGIES]):
"""
@notice
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.
@dev
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.
@param queue
The array of addresses to use as the new withdrawal queue. This is
order sensitive.
"""
assert msg.sender in [self.management, self.governance]
# HACK: Temporary until Vyper adds support for Dynamic arrays
old_queue: address[MAXIMUM_STRATEGIES] = empty(address[MAXIMUM_STRATEGIES])
for i in range(MAXIMUM_STRATEGIES):
old_queue[i] = self.withdrawalQueue[i]
if queue[i] == ZERO_ADDRESS:
# NOTE: Cannot use this method to remove entries from the queue
assert old_queue[i] == ZERO_ADDRESS
break
# NOTE: Cannot use this method to add more entries to the queue
assert old_queue[i] != ZERO_ADDRESS
assert self.strategies[queue[i]].activation > 0
existsInOldQueue: bool = False
for j in range(MAXIMUM_STRATEGIES):
if queue[j] == ZERO_ADDRESS:
existsInOldQueue = True
break
if queue[i] == old_queue[j]:
# NOTE: Ensure that every entry in queue prior to reordering exists now
existsInOldQueue = True
if j <= i:
# NOTE: This will only check for duplicate entries in queue after `i`
continue
assert queue[i] != queue[j] # dev: do not add duplicate strategies
assert existsInOldQueue # dev: do not add new strategies
self.withdrawalQueue[i] = queue[i]
log UpdateWithdrawalQueue(queue)
@internal
def erc20_safe_transfer(token: address, receiver: address, amount: uint256):
# Used only to send tokens that are not the type managed by this Vault.
# HACK: Used to handle non-compliant tokens like USDT
response: Bytes[32] = raw_call(
token,
concat(
method_id("transfer(address,uint256)"),
convert(receiver, bytes32),
convert(amount, bytes32),
),
max_outsize=32,
)
if len(response) > 0:
assert convert(response, bool), "Transfer failed!"
@internal
def erc20_safe_transferFrom(token: address, sender: address, receiver: address, amount: uint256):
# Used only to send tokens that are not the type managed by this Vault.
# HACK: Used to handle non-compliant tokens like USDT
response: Bytes[32] = raw_call(
token,
concat(
method_id("transferFrom(address,address,uint256)"),
convert(sender, bytes32),
convert(receiver, bytes32),
convert(amount, bytes32),
),
max_outsize=32,
)
if len(response) > 0:
assert convert(response, bool), "Transfer failed!"
@internal
def _transfer(sender: address, receiver: address, amount: uint256):
# See note on `transfer()`.
# Protect people from accidentally sending their shares to bad places
assert receiver not in [self, ZERO_ADDRESS]
self.balanceOf[sender] -= amount
self.balanceOf[receiver] += amount
log Transfer(sender, receiver, amount)
@external
def transfer(receiver: address, amount: uint256) -> bool:
"""
@notice
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.
@param receiver
The address shares are being transferred to. Must not be this contract's
address, must not be 0x0.
@param amount The quantity of shares to transfer.
@return
True if transfer is sent to an address other than this contract's or
0x0, otherwise the transaction will fail.
"""
self._transfer(msg.sender, receiver, amount)
return True
@external
def transferFrom(sender: address, receiver: address, amount: uint256) -> bool:
"""
@notice
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`.
@param sender The address shares are being transferred from.
@param receiver
The address shares are being transferred to. Must not be this contract's
address, must not be 0x0.
@param amount The quantity of shares to transfer.
@return
True if transfer is sent to an address other than this contract's or
0x0, otherwise the transaction will fail.
"""
# Unlimited approval (saves an SSTORE)
if (self.allowance[sender][msg.sender] < MAX_UINT256):
allowance: uint256 = self.allowance[sender][msg.sender] - amount
self.allowance[sender][msg.sender] = allowance
# NOTE: Allows log filters to have a full accounting of allowance changes
log Approval(sender, msg.sender, allowance)
self._transfer(sender, receiver, amount)
return True
@external
def approve(spender: address, amount: uint256) -> bool:
"""
@dev 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
@param spender The address which will spend the funds.
@param amount The amount of tokens to be spent.
"""
self.allowance[msg.sender][spender] = amount
log Approval(msg.sender, spender, amount)
return True
@external
def increaseAllowance(spender: address, amount: uint256) -> bool:
"""
@dev 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
@param spender The address which will spend the funds.
@param amount The amount of tokens to increase the allowance by.
"""
self.allowance[msg.sender][spender] += amount
log Approval(msg.sender, spender, self.allowance[msg.sender][spender])
return True
@external
def decreaseAllowance(spender: address, amount: uint256) -> bool:
"""
@dev 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
@param spender The address which will spend the funds.
@param amount The amount of tokens to decrease the allowance by.
"""
self.allowance[msg.sender][spender] -= amount
log Approval(msg.sender, spender, self.allowance[msg.sender][spender])
return True
@external
def permit(owner: address, spender: address, amount: uint256, expiry: uint256, signature: Bytes[65]) -> bool:
"""
@notice
Approves spender by owner's signature to expend owner's tokens.
See https://eips.ethereum.org/EIPS/eip-2612.
@param owner The address which is a source of funds and has signed the Permit.
@param spender The address which is allowed to spend the funds.
@param amount The amount of tokens to be spent.
@param expiry The timestamp after which the Permit is no longer valid.
@param signature A valid secp256k1 signature of Permit by owner encoded as r, s, v.
@return True, if transaction completes successfully
"""
assert owner != ZERO_ADDRESS # dev: invalid owner
assert expiry == 0 or expiry >= block.timestamp # dev: permit expired
nonce: uint256 = self.nonces[owner]
digest: bytes32 = keccak256(
concat(
b'\x19\x01',
self.DOMAIN_SEPARATOR,
keccak256(
concat(
PERMIT_TYPE_HASH,
convert(owner, bytes32),
convert(spender, bytes32),
convert(amount, bytes32),
convert(nonce, bytes32),
convert(expiry, bytes32),
)
)
)
)
# NOTE: signature is packed as r, s, v
r: uint256 = convert(slice(signature, 0, 32), uint256)
s: uint256 = convert(slice(signature, 32, 32), uint256)
v: uint256 = convert(slice(signature, 64, 1), uint256)
assert ecrecover(digest, v, r, s) == owner # dev: invalid signature
self.allowance[owner][spender] = amount
self.nonces[owner] = nonce + 1
log Approval(owner, spender, amount)
return True
@view
@internal
def _totalAssets() -> uint256:
# See note on `totalAssets()`.
return self.token.balanceOf(self) + self.totalDebt
@view
@external
def totalAssets() -> uint256:
"""
@notice
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 The total assets under control of this Vault.
"""
return self._totalAssets()
@view
@internal
def _calculateLockedProfit() -> uint256:
lockedFundsRatio: uint256 = (block.timestamp - self.lastReport) * self.lockedProfitDegradation
if(lockedFundsRatio < DEGRADATION_COEFFICIENT):
lockedProfit: uint256 = self.lockedProfit
return lockedProfit - (
lockedFundsRatio
* lockedProfit
/ DEGRADATION_COEFFICIENT
)
else:
return 0
@internal
def _issueSharesForAmount(to: address, amount: uint256) -> uint256:
# Issues `amount` Vault shares to `to`.
# Shares must be issued prior to taking on new collateral, or
# calculation will be wrong. This means that only *trusted* tokens
# (with no capability for exploitative behavior) can be used.
shares: uint256 = 0
# HACK: Saves 2 SLOADs (~200 gas, post-Berlin)
totalSupply: uint256 = self.totalSupply
if totalSupply > 0:
# Mint amount of shares based on what the Vault is managing overall
# NOTE: if sqrt(token.totalSupply()) > 1e39, this could potentially revert
freeFunds: uint256 = self._totalAssets() - self._calculateLockedProfit()
shares = amount * totalSupply / freeFunds # dev: no free funds
else:
# No existing shares, so mint 1:1
shares = amount
assert shares != 0 # dev: division rounding resulted in zero
# Mint new shares
self.totalSupply = totalSupply + shares
self.balanceOf[to] += shares
log Transfer(ZERO_ADDRESS, to, shares)
return shares
@external
@nonreentrant("withdraw")
def deposit(_amount: uint256 = MAX_UINT256, recipient: address = msg.sender) -> uint256:
"""
@notice
Deposits `_amount` `token`, issuing shares to `recipient`. If the
Vault is in Emergency Shutdown, deposits will not be accepted and this
call will fail.
@dev
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".
@param _amount The quantity of tokens to deposit, defaults to all.
@param recipient
The address to issue the shares in this Vault to. Defaults to the
caller's address.
@return The issued Vault shares.
"""
assert not self.emergencyShutdown # Deposits are locked out
assert recipient not in [self, ZERO_ADDRESS]
amount: uint256 = _amount
# If _amount not specified, transfer the full token balance,
# up to deposit limit
if amount == MAX_UINT256:
amount = min(
self.depositLimit - self._totalAssets(),
self.token.balanceOf(msg.sender),
)
else:
# Ensure deposit limit is respected
assert self._totalAssets() + amount <= self.depositLimit
# Ensure we are depositing something
assert amount > 0
# Issue new shares (needs to be done before taking deposit to be accurate)
# Shares are issued to recipient (may be different from msg.sender)
# See @dev note, above.
shares: uint256 = self._issueSharesForAmount(recipient, amount)
# Tokens are transferred from msg.sender (may be different from _recipient)
self.erc20_safe_transferFrom(self.token.address, msg.sender, self, amount)
return shares # Just in case someone wants them
@view
@internal
def _shareValue(shares: uint256) -> uint256:
# Returns price = 1:1 if vault is empty
if self.totalSupply == 0:
return shares
# Determines the current value of `shares`.
# NOTE: if sqrt(Vault.totalAssets()) >>> 1e39, this could potentially revert
freeFunds: uint256 = self._totalAssets() - self._calculateLockedProfit()
return (
shares
* freeFunds
/ self.totalSupply
)
@view
@internal
def _sharesForAmount(amount: uint256) -> uint256:
# Determines how many shares `amount` of token would receive.
# See dev note on `deposit`.
if self._totalAssets() > 0:
# NOTE: if sqrt(token.totalSupply()) > 1e37, this could potentially revert
return (
amount
* self.totalSupply
/ self._totalAssets()
)
else:
return 0
@view
@external
def maxAvailableShares() -> uint256:
"""
@notice
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.
@dev
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 The total quantity of shares this Vault can provide.
"""
shares: uint256 = self._sharesForAmount(self.token.balanceOf(self))
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break
shares += self._sharesForAmount(self.strategies[strategy].totalDebt)
return shares
@internal
def _reportLoss(strategy: address, loss: uint256):
# Loss can only be up the amount of debt issued to strategy
totalDebt: uint256 = self.strategies[strategy].totalDebt
assert totalDebt >= loss
# Also, make sure we reduce our trust with the strategy by the amount of loss
if self.debtRatio != 0: # if vault with single strategy that is set to EmergencyOne
# NOTE: The context to this calculation is different than the calculation in `_reportLoss`,
# this calculation intentionally approximates via `totalDebt` to avoid manipulatable results
ratio_change: uint256 = min(
# NOTE: This calculation isn't 100% precise, the adjustment is ~10%-20% more severe due to EVM math
loss * self.debtRatio / self.totalDebt,
self.strategies[strategy].debtRatio,
)
self.strategies[strategy].debtRatio -= ratio_change
self.debtRatio -= ratio_change
# Finally, adjust our strategy's parameters by the loss
self.strategies[strategy].totalLoss += loss
self.strategies[strategy].totalDebt = totalDebt - loss
self.totalDebt -= loss
@external
@nonreentrant("withdraw")
def withdraw(
maxShares: uint256 = MAX_UINT256,
recipient: address = msg.sender,
maxLoss: uint256 = 1, # 0.01% [BPS]
) -> uint256:
"""
@notice
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.
@dev
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.
@param maxShares
How many shares to try and redeem for tokens, defaults to all.
@param recipient
The address to issue the shares in this Vault to. Defaults to the
caller's address.
@param maxLoss
The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%.
@return The quantity of tokens redeemed for `_shares`.
"""
shares: uint256 = maxShares # May reduce this number below
# Max Loss is <=100%, revert otherwise
assert maxLoss <= MAX_BPS
# If _shares not specified, transfer full share balance
if shares == MAX_UINT256:
shares = self.balanceOf[msg.sender]
# Limit to only the shares they own
assert shares <= self.balanceOf[msg.sender]
# Ensure we are withdrawing something
assert shares > 0
# See @dev note, above.
value: uint256 = self._shareValue(shares)
totalLoss: uint256 = 0
if value > self.token.balanceOf(self):
# We need to go get some from our strategies in the withdrawal queue
# NOTE: This performs forced withdrawals from each Strategy. During
# forced withdrawal, a Strategy may realize a loss. That loss
# is reported back to the Vault, and the will affect the amount
# of tokens that the withdrawer receives for their shares. They
# can optionally specify the maximum acceptable loss (in BPS)
# to prevent excessive losses on their withdrawals (which may
# happen in certain edge cases where Strategies realize a loss)
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break # We've exhausted the queue
vault_balance: uint256 = self.token.balanceOf(self)
if value <= vault_balance:
break # We're done withdrawing
amountNeeded: uint256 = value - vault_balance
# NOTE: Don't withdraw more than the debt so that Strategy can still
# continue to work based on the profits it has
# NOTE: This means that user will lose out on any profits that each
# Strategy in the queue would return on next harvest, benefiting others
amountNeeded = min(amountNeeded, self.strategies[strategy].totalDebt)
if amountNeeded == 0:
continue # Nothing to withdraw from this Strategy, try the next one
# Force withdraw amount from each Strategy in the order set by governance
loss: uint256 = Strategy(strategy).withdraw(amountNeeded)
withdrawn: uint256 = self.token.balanceOf(self) - vault_balance
# NOTE: Withdrawer incurs any losses from liquidation
if loss > 0:
value -= loss
totalLoss += loss
self._reportLoss(strategy, loss)
# Reduce the Strategy's debt by the amount withdrawn ("realized returns")
# NOTE: This doesn't add to returns as it's not earned by "normal means"
self.strategies[strategy].totalDebt -= withdrawn
self.totalDebt -= withdrawn
# NOTE: We have withdrawn everything possible out of the withdrawal queue
# but we still don't have enough to fully pay them back, so adjust
# to the total amount we've freed up through forced withdrawals
vault_balance: uint256 = self.token.balanceOf(self)
if value > vault_balance:
value = vault_balance
# NOTE: Burn # of shares that corresponds to what Vault has on-hand,
# including the losses that were incurred above during withdrawals
shares = self._sharesForAmount(value + totalLoss)
# NOTE: This loss protection is put in place to revert if losses from
# withdrawing are more than what is considered acceptable.
assert totalLoss <= maxLoss * (value + totalLoss) / MAX_BPS
# Burn shares (full value of what is being withdrawn)
self.totalSupply -= shares
self.balanceOf[msg.sender] -= shares
log Transfer(msg.sender, ZERO_ADDRESS, shares)
# Withdraw remaining balance to _recipient (may be different to msg.sender) (minus fee)
self.erc20_safe_transfer(self.token.address, recipient, value)
return value
@view
@external
def pricePerShare() -> uint256:
"""
@notice Gives the price for a single Vault share.
@dev See dev note on `withdraw`.
@return The value of a single share.
"""
return self._shareValue(10 ** self.decimals)
@internal
def _organizeWithdrawalQueue():
# Reorganize `withdrawalQueue` based on premise that if there is an
# empty value between two actual values, then the empty value should be
# replaced by the later value.
# NOTE: Relative ordering of non-zero values is maintained.
offset: uint256 = 0
for idx in range(MAXIMUM_STRATEGIES):
strategy: address = self.withdrawalQueue[idx]
if strategy == ZERO_ADDRESS:
offset += 1 # how many values we need to shift, always `<= idx`
elif offset > 0:
self.withdrawalQueue[idx - offset] = strategy
self.withdrawalQueue[idx] = ZERO_ADDRESS
@external
def addStrategy(
strategy: address,
debtRatio: uint256,
minDebtPerHarvest: uint256,
maxDebtPerHarvest: uint256,
performanceFee: uint256,
):
"""
@notice
Add a Strategy to the Vault.
This may only be called by governance.
@dev
The Strategy will be appended to `withdrawalQueue`, call
`setWithdrawalQueue` to change the order.
@param strategy The address of the Strategy to add.
@param debtRatio
The share of the total assets in the `vault that the `strategy` has access to.
@param minDebtPerHarvest
Lower limit on the increase of debt since last harvest
@param maxDebtPerHarvest
Upper limit on the increase of debt since last harvest
@param performanceFee
The fee the strategist will receive based on this Vault's performance.
"""
# Check if queue is full
assert self.withdrawalQueue[MAXIMUM_STRATEGIES - 1] == ZERO_ADDRESS
# Check calling conditions
assert not self.emergencyShutdown
assert msg.sender == self.governance
# Check strategy configuration
assert strategy != ZERO_ADDRESS
assert self.strategies[strategy].activation == 0
assert self == Strategy(strategy).vault()
assert self.token.address == Strategy(strategy).want()
# Check strategy parameters
assert self.debtRatio + debtRatio <= MAX_BPS
assert minDebtPerHarvest <= maxDebtPerHarvest
assert performanceFee <= MAX_BPS / 2
# Add strategy to approved strategies
self.strategies[strategy] = StrategyParams({
performanceFee: performanceFee,
activation: block.timestamp,
debtRatio: debtRatio,
minDebtPerHarvest: minDebtPerHarvest,
maxDebtPerHarvest: maxDebtPerHarvest,
lastReport: block.timestamp,
totalDebt: 0,
totalGain: 0,
totalLoss: 0,
})
log StrategyAdded(strategy, debtRatio, minDebtPerHarvest, maxDebtPerHarvest, performanceFee)
# Update Vault parameters
self.debtRatio += debtRatio
# Add strategy to the end of the withdrawal queue
self.withdrawalQueue[MAXIMUM_STRATEGIES - 1] = strategy
self._organizeWithdrawalQueue()
@external
def updateStrategyDebtRatio(
strategy: address,
debtRatio: uint256,
):
"""
@notice
Change the quantity of assets `strategy` may manage.
This may be called by governance or management.
@param strategy The Strategy to update.
@param debtRatio The quantity of assets `strategy` may now manage.
"""
assert msg.sender in [self.management, self.governance]
assert self.strategies[strategy].activation > 0
self.debtRatio -= self.strategies[strategy].debtRatio
self.strategies[strategy].debtRatio = debtRatio
self.debtRatio += debtRatio
assert self.debtRatio <= MAX_BPS
log StrategyUpdateDebtRatio(strategy, debtRatio)
@external
def updateStrategyMinDebtPerHarvest(
strategy: address,
minDebtPerHarvest: uint256,
):
"""
@notice
Change the quantity assets per block this Vault may deposit to or
withdraw from `strategy`.
This may only be called by governance or management.
@param strategy The Strategy to update.
@param minDebtPerHarvest
Lower limit on the increase of debt since last harvest
"""
assert msg.sender in [self.management, self.governance]
assert self.strategies[strategy].activation > 0
assert self.strategies[strategy].maxDebtPerHarvest >= minDebtPerHarvest
self.strategies[strategy].minDebtPerHarvest = minDebtPerHarvest
log StrategyUpdateMinDebtPerHarvest(strategy, minDebtPerHarvest)
@external
def updateStrategyMaxDebtPerHarvest(
strategy: address,
maxDebtPerHarvest: uint256,
):
"""
@notice
Change the quantity assets per block this Vault may deposit to or
withdraw from `strategy`.
This may only be called by governance or management.
@param strategy The Strategy to update.
@param maxDebtPerHarvest
Upper limit on the increase of debt since last harvest
"""
assert msg.sender in [self.management, self.governance]
assert self.strategies[strategy].activation > 0
assert self.strategies[strategy].minDebtPerHarvest <= maxDebtPerHarvest
self.strategies[strategy].maxDebtPerHarvest = maxDebtPerHarvest
log StrategyUpdateMaxDebtPerHarvest(strategy, maxDebtPerHarvest)
@external
def updateStrategyPerformanceFee(
strategy: address,
performanceFee: uint256,
):
"""
@notice
Change the fee the strategist will receive based on this Vault's
performance.
This may only be called by governance.
@param strategy The Strategy to update.
@param performanceFee The new fee the strategist will receive.
"""
assert msg.sender == self.governance
assert performanceFee <= MAX_BPS / 2
assert self.strategies[strategy].activation > 0
self.strategies[strategy].performanceFee = performanceFee
log StrategyUpdatePerformanceFee(strategy, performanceFee)
@internal
def _revokeStrategy(strategy: address):
self.debtRatio -= self.strategies[strategy].debtRatio
self.strategies[strategy].debtRatio = 0
log StrategyRevoked(strategy)
@external
def migrateStrategy(oldVersion: address, newVersion: address):
"""
@notice
Migrates a Strategy, including all assets from `oldVersion` to
`newVersion`.
This may only be called by governance.
@dev
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.
@param oldVersion The existing Strategy to migrate from.
@param newVersion The new Strategy to migrate to.
"""
assert msg.sender == self.governance
assert newVersion != ZERO_ADDRESS
assert self.strategies[oldVersion].activation > 0
assert self.strategies[newVersion].activation == 0
strategy: StrategyParams = self.strategies[oldVersion]
self._revokeStrategy(oldVersion)
# _revokeStrategy will lower the debtRatio
self.debtRatio += strategy.debtRatio
# Debt is migrated to new strategy
self.strategies[oldVersion].totalDebt = 0
self.strategies[newVersion] = StrategyParams({
performanceFee: strategy.performanceFee,
# NOTE: use last report for activation time, so E[R] calc works
activation: strategy.lastReport,
debtRatio: strategy.debtRatio,
minDebtPerHarvest: strategy.minDebtPerHarvest,
maxDebtPerHarvest: strategy.maxDebtPerHarvest,
lastReport: strategy.lastReport,
totalDebt: strategy.totalDebt,
totalGain: 0,
totalLoss: 0,
})
Strategy(oldVersion).migrate(newVersion)
log StrategyMigrated(oldVersion, newVersion)
for idx in range(MAXIMUM_STRATEGIES):
if self.withdrawalQueue[idx] == oldVersion:
self.withdrawalQueue[idx] = newVersion
return # Don't need to reorder anything because we swapped
@external
def revokeStrategy(strategy: address = msg.sender):
"""
@notice
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.
@param strategy The Strategy to revoke.
"""
assert msg.sender in [strategy, self.governance, self.guardian]
assert self.strategies[strategy].debtRatio != 0 # dev: already zero
self._revokeStrategy(strategy)
@external
def addStrategyToQueue(strategy: address):
"""
@notice
Adds `strategy` to `withdrawalQueue`.
This may only be called by governance or management.
@dev
The Strategy will be appended to `withdrawalQueue`, call
`setWithdrawalQueue` to change the order.
@param strategy The Strategy to add.
"""
assert msg.sender in [self.management, self.governance]
# Must be a current Strategy
assert self.strategies[strategy].activation > 0
# Can't already be in the queue
last_idx: uint256 = 0
for s in self.withdrawalQueue:
if s == ZERO_ADDRESS:
break
assert s != strategy
last_idx += 1
# Check if queue is full
assert last_idx < MAXIMUM_STRATEGIES
self.withdrawalQueue[MAXIMUM_STRATEGIES - 1] = strategy
self._organizeWithdrawalQueue()
log StrategyAddedToQueue(strategy)
@external
def removeStrategyFromQueue(strategy: address):
"""
@notice
Remove `strategy` from `withdrawalQueue`.
This may only be called by governance or management.
@dev
We don't do this with revokeStrategy because it should still
be possible to withdraw from the Strategy if it's unwinding.
@param strategy The Strategy to remove.
"""
assert msg.sender in [self.management, self.governance]
for idx in range(MAXIMUM_STRATEGIES):
if self.withdrawalQueue[idx] == strategy:
self.withdrawalQueue[idx] = ZERO_ADDRESS
self._organizeWithdrawalQueue()
log StrategyRemovedFromQueue(strategy)
return # We found the right location and cleared it
raise # We didn't find the Strategy in the queue
@view
@internal
def _debtOutstanding(strategy: address) -> uint256:
# See note on `debtOutstanding()`.
if self.debtRatio == 0:
return self.strategies[strategy].totalDebt
strategy_debtLimit: uint256 = (
self.strategies[strategy].debtRatio
* self._totalAssets()
/ MAX_BPS
)
strategy_totalDebt: uint256 = self.strategies[strategy].totalDebt
if self.emergencyShutdown:
return strategy_totalDebt
elif strategy_totalDebt <= strategy_debtLimit:
return 0
else:
return strategy_totalDebt - strategy_debtLimit
@view
@external
def debtOutstanding(strategy: address = msg.sender) -> uint256:
"""
@notice
Determines if `strategy` is past its debt limit and if any tokens
should be withdrawn to the Vault.
@param strategy The Strategy to check. Defaults to the caller.
@return The quantity of tokens to withdraw.
"""
return self._debtOutstanding(strategy)
@view
@internal
def _creditAvailable(strategy: address) -> uint256:
# See note on `creditAvailable()`.
if self.emergencyShutdown:
return 0
vault_totalAssets: uint256 = self._totalAssets()
vault_debtLimit: uint256 = self.debtRatio * vault_totalAssets / MAX_BPS
vault_totalDebt: uint256 = self.totalDebt
strategy_debtLimit: uint256 = self.strategies[strategy].debtRatio * vault_totalAssets / MAX_BPS
strategy_totalDebt: uint256 = self.strategies[strategy].totalDebt
strategy_minDebtPerHarvest: uint256 = self.strategies[strategy].minDebtPerHarvest
strategy_maxDebtPerHarvest: uint256 = self.strategies[strategy].maxDebtPerHarvest
# Exhausted credit line
if strategy_debtLimit <= strategy_totalDebt or vault_debtLimit <= vault_totalDebt:
return 0
# Start with debt limit left for the Strategy
available: uint256 = strategy_debtLimit - strategy_totalDebt
# Adjust by the global debt limit left
available = min(available, vault_debtLimit - vault_totalDebt)
# Can only borrow up to what the contract has in reserve
# NOTE: Running near 100% is discouraged
available = min(available, self.token.balanceOf(self))
# Adjust by min and max borrow limits (per harvest)
# NOTE: min increase can be used to ensure that if a strategy has a minimum
# amount of capital needed to purchase a position, it's not given capital
# it can't make use of yet.
# NOTE: max increase is used to make sure each harvest isn't bigger than what
# is authorized. This combined with adjusting min and max periods in
# `BaseStrategy` can be used to effect a "rate limit" on capital increase.
if available < strategy_minDebtPerHarvest:
return 0
else:
return min(available, strategy_maxDebtPerHarvest)
@view
@external
def creditAvailable(strategy: address = msg.sender) -> uint256:
"""
@notice
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.
@param strategy The Strategy to check. Defaults to caller.
@return The quantity of tokens available for the Strategy to draw on.
"""
return self._creditAvailable(strategy)
@view
@internal
def _expectedReturn(strategy: address) -> uint256:
# See note on `expectedReturn()`.
strategy_lastReport: uint256 = self.strategies[strategy].lastReport
timeSinceLastHarvest: uint256 = block.timestamp - strategy_lastReport
totalHarvestTime: uint256 = strategy_lastReport - self.strategies[strategy].activation
# NOTE: If either `timeSinceLastHarvest` or `totalHarvestTime` is 0, we can short-circuit to `0`
if timeSinceLastHarvest > 0 and totalHarvestTime > 0 and Strategy(strategy).isActive():
# NOTE: Unlikely to throw unless strategy accumalates >1e68 returns
# NOTE: Calculate average over period of time where harvests have occured in the past
return (
self.strategies[strategy].totalGain
* timeSinceLastHarvest
/ totalHarvestTime
)
else:
return 0 # Covers the scenario when block.timestamp == activation
@view
@external
def availableDepositLimit() -> uint256:
if self.depositLimit > self._totalAssets():
return self.depositLimit - self._totalAssets()
else:
return 0
@view
@external
def expectedReturn(strategy: address = msg.sender) -> uint256:
"""
@notice
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).
@param strategy The Strategy to determine the expected return for. Defaults to caller.
@return
The anticipated amount `strategy` should make on its investment
since its last report.
"""
return self._expectedReturn(strategy)
@internal
def _assessFees(strategy: address, gain: uint256) -> uint256:
# Issue new shares to cover fees
# NOTE: In effect, this reduces overall share price by the combined fee
# NOTE: may throw if Vault.totalAssets() > 1e64, or not called for more than a year
duration: uint256 = block.timestamp - self.strategies[strategy].lastReport
assert duration != 0 # can't assessFees twice within the same block
if gain == 0:
# NOTE: The fees are not charged if there hasn't been any gains reported
return 0
management_fee: uint256 = (
(
(self.strategies[strategy].totalDebt - Strategy(strategy).delegatedAssets())
* duration
* self.managementFee
)
/ MAX_BPS
/ SECS_PER_YEAR
)
# NOTE: Applies if Strategy is not shutting down, or it is but all debt paid off
# NOTE: No fee is taken when a Strategy is unwinding it's position, until all debt is paid
strategist_fee: uint256 = (
gain
* self.strategies[strategy].performanceFee
/ MAX_BPS
)
# NOTE: Unlikely to throw unless strategy reports >1e72 harvest profit
performance_fee: uint256 = gain * self.performanceFee / MAX_BPS
# NOTE: This must be called prior to taking new collateral,
# or the calculation will be wrong!
# NOTE: This must be done at the same time, to ensure the relative
# ratio of governance_fee : strategist_fee is kept intact
total_fee: uint256 = performance_fee + strategist_fee + management_fee
# ensure total_fee is not more than gain
if total_fee > gain:
total_fee = gain
if total_fee > 0: # NOTE: If mgmt fee is 0% and no gains were realized, skip
reward: uint256 = self._issueSharesForAmount(self, total_fee)
# Send the rewards out as new shares in this Vault
if strategist_fee > 0: # NOTE: Guard against DIV/0 fault
# NOTE: Unlikely to throw unless sqrt(reward) >>> 1e39
strategist_reward: uint256 = (
strategist_fee
* reward
/ total_fee
)
self._transfer(self, strategy, strategist_reward)
# NOTE: Strategy distributes rewards at the end of harvest()
# NOTE: Governance earns any dust leftover from flooring math above
if self.balanceOf[self] > 0:
self._transfer(self, self.rewards, self.balanceOf[self])
return total_fee
@external
def report(gain: uint256, loss: uint256, _debtPayment: uint256) -> uint256:
"""
@notice
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.
@dev
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.
@param 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
@param 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.
@param _debtPayment
Amount Strategy has made available to cover outstanding debt
@return Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown).
"""
# Only approved strategies can call this function
assert self.strategies[msg.sender].activation > 0
# No lying about total available to withdraw!
assert self.token.balanceOf(msg.sender) >= gain + _debtPayment
# We have a loss to report, do it before the rest of the calculations
if loss > 0:
self._reportLoss(msg.sender, loss)
# Assess both management fee and performance fee, and issue both as shares of the vault
totalFees: uint256 = self._assessFees(msg.sender, gain)
# Returns are always "realized gains"
self.strategies[msg.sender].totalGain += gain
# Compute the line of credit the Vault is able to offer the Strategy (if any)
credit: uint256 = self._creditAvailable(msg.sender)
# Outstanding debt the Strategy wants to take back from the Vault (if any)
# NOTE: debtOutstanding <= StrategyParams.totalDebt
debt: uint256 = self._debtOutstanding(msg.sender)
debtPayment: uint256 = min(_debtPayment, debt)
if debtPayment > 0:
self.strategies[msg.sender].totalDebt -= debtPayment
self.totalDebt -= debtPayment
debt -= debtPayment
# NOTE: `debt` is being tracked for later
# Update the actual debt based on the full credit we are extending to the Strategy
# or the returns if we are taking funds back
# NOTE: credit + self.strategies[msg.sender].totalDebt is always < self.debtLimit
# NOTE: At least one of `credit` or `debt` is always 0 (both can be 0)
if credit > 0:
self.strategies[msg.sender].totalDebt += credit
self.totalDebt += credit
# Give/take balance to Strategy, based on the difference between the reported gains
# (if any), the debt payment (if any), the credit increase we are offering (if any),
# and the debt needed to be paid off (if any)
# NOTE: This is just used to adjust the balance of tokens between the Strategy and
# the Vault based on the Strategy's debt limit (as well as the Vault's).
totalAvail: uint256 = gain + debtPayment
if totalAvail < credit: # credit surplus, give to Strategy
self.erc20_safe_transfer(self.token.address, msg.sender, credit - totalAvail)
elif totalAvail > credit: # credit deficit, take from Strategy
self.erc20_safe_transferFrom(self.token.address, msg.sender, self, totalAvail - credit)
# else, don't do anything because it is balanced
# Profit is locked and gradually released per block
# NOTE: compute current locked profit and replace with sum of current and new
lockedProfitBeforeLoss: uint256 = self._calculateLockedProfit() + gain - totalFees
if lockedProfitBeforeLoss > loss:
self.lockedProfit = lockedProfitBeforeLoss - loss
else:
self.lockedProfit = 0
# Update reporting time
self.strategies[msg.sender].lastReport = block.timestamp
self.lastReport = block.timestamp
log StrategyReported(
msg.sender,
gain,
loss,
debtPayment,
self.strategies[msg.sender].totalGain,
self.strategies[msg.sender].totalLoss,
self.strategies[msg.sender].totalDebt,
credit,
self.strategies[msg.sender].debtRatio,
)
if self.strategies[msg.sender].debtRatio == 0 or self.emergencyShutdown:
# Take every last penny the Strategy has (Emergency Exit/revokeStrategy)
# NOTE: This is different than `debt` in order to extract *all* of the returns
return Strategy(msg.sender).estimatedTotalAssets()
else:
# Otherwise, just return what we have as debt outstanding
return debt
@external
def sweep(token: address, amount: uint256 = MAX_UINT256):
"""
@notice
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.
@param token The token to transfer out of this vault.
@param amount The quantity or tokenId to transfer out.
"""
assert msg.sender == self.governance
# Can't be used to steal what this Vault is protecting
assert token != self.token.address
value: uint256 = amount
if value == MAX_UINT256:
value = ERC20(token).balanceOf(self)
self.erc20_safe_transfer(token, self.governance, value)File 3 of 4: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.18;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return this.balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/File 4 of 4: Vyper_contract
# @version 0.2.12
"""
@title Yearn Token Vault
@license GNU AGPLv3
@author yearn.finance
@notice
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/master/SPECIFICATION.md
"""
API_VERSION: constant(String[28]) = "0.4.2"
from vyper.interfaces import ERC20
implements: ERC20
interface DetailedERC20:
def name() -> String[42]: view
def symbol() -> String[20]: view
def decimals() -> uint256: view
interface Strategy:
def want() -> address: view
def vault() -> address: view
def isActive() -> bool: view
def delegatedAssets() -> uint256: view
def estimatedTotalAssets() -> uint256: view
def withdraw(_amount: uint256) -> uint256: nonpayable
def migrate(_newStrategy: address): nonpayable
event Transfer:
sender: indexed(address)
receiver: indexed(address)
value: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
value: uint256
name: public(String[64])
symbol: public(String[32])
decimals: public(uint256)
balanceOf: public(HashMap[address, uint256])
allowance: public(HashMap[address, HashMap[address, uint256]])
totalSupply: public(uint256)
token: public(ERC20)
governance: public(address)
management: public(address)
guardian: public(address)
pendingGovernance: address
struct StrategyParams:
performanceFee: uint256 # Strategist's fee (basis points)
activation: uint256 # Activation block.timestamp
debtRatio: uint256 # Maximum borrow amount (in BPS of total assets)
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
lastReport: uint256 # block.timestamp of the last time a report occured
totalDebt: uint256 # Total outstanding debt that Strategy has
totalGain: uint256 # Total returns that Strategy has realized for Vault
totalLoss: uint256 # Total losses that Strategy has realized for Vault
event StrategyAdded:
strategy: indexed(address)
debtRatio: uint256 # Maximum borrow amount (in BPS of total assets)
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
performanceFee: uint256 # Strategist's fee (basis points)
event StrategyReported:
strategy: indexed(address)
gain: uint256
loss: uint256
debtPaid: uint256
totalGain: uint256
totalLoss: uint256
totalDebt: uint256
debtAdded: uint256
debtRatio: uint256
event UpdateGovernance:
governance: address # New active governance
event UpdateManagement:
management: address # New active manager
event UpdateRewards:
rewards: address # New active rewards recipient
event UpdateDepositLimit:
depositLimit: uint256 # New active deposit limit
event UpdatePerformanceFee:
performanceFee: uint256 # New active performance fee
event UpdateManagementFee:
managementFee: uint256 # New active management fee
event UpdateGuardian:
guardian: address # Address of the active guardian
event EmergencyShutdown:
active: bool # New emergency shutdown state (if false, normal operation enabled)
event UpdateWithdrawalQueue:
queue: address[MAXIMUM_STRATEGIES] # New active withdrawal queue
event StrategyUpdateDebtRatio:
strategy: indexed(address) # Address of the strategy for the debt ratio adjustment
debtRatio: uint256 # The new debt limit for the strategy (in BPS of total assets)
event StrategyUpdateMinDebtPerHarvest:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
minDebtPerHarvest: uint256 # Lower limit on the increase of debt since last harvest
event StrategyUpdateMaxDebtPerHarvest:
strategy: indexed(address) # Address of the strategy for the rate limit adjustment
maxDebtPerHarvest: uint256 # Upper limit on the increase of debt since last harvest
event StrategyUpdatePerformanceFee:
strategy: indexed(address) # Address of the strategy for the performance fee adjustment
performanceFee: uint256 # The new performance fee for the strategy
event StrategyMigrated:
oldVersion: indexed(address) # Old version of the strategy to be migrated
newVersion: indexed(address) # New version of the strategy
event StrategyRevoked:
strategy: indexed(address) # Address of the strategy that is revoked
event StrategyRemovedFromQueue:
strategy: indexed(address) # Address of the strategy that is removed from the withdrawal queue
event StrategyAddedToQueue:
strategy: indexed(address) # Address of the strategy that is added to the withdrawal queue
# NOTE: Track the total for overhead targeting purposes
strategies: public(HashMap[address, StrategyParams])
MAXIMUM_STRATEGIES: constant(uint256) = 20
DEGRADATION_COEFFICIENT: constant(uint256) = 10 ** 18
# Ordering that `withdraw` uses to determine which strategies to pull funds from
# NOTE: Does *NOT* have to match the ordering of all the current strategies that
# exist, but it is recommended that it does or else withdrawal depth is
# limited to only those inside the queue.
# NOTE: Ordering is determined by governance, and should be balanced according
# to risk, slippage, and/or volatility. Can also be ordered to increase the
# withdrawal speed of a particular Strategy.
# NOTE: The first time a ZERO_ADDRESS is encountered, it stops withdrawing
withdrawalQueue: public(address[MAXIMUM_STRATEGIES])
emergencyShutdown: public(bool)
depositLimit: public(uint256) # Limit for totalAssets the Vault can hold
debtRatio: public(uint256) # Debt ratio for the Vault across all strategies (in BPS, <= 10k)
totalDebt: public(uint256) # Amount of tokens that all strategies have borrowed
lastReport: public(uint256) # block.timestamp of last report
activation: public(uint256) # block.timestamp of contract deployment
lockedProfit: public(uint256) # how much profit is locked and cant be withdrawn
lockedProfitDegradation: public(uint256) # rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block
rewards: public(address) # Rewards contract where Governance fees are sent to
# Governance Fee for management of Vault (given to `rewards`)
managementFee: public(uint256)
# Governance Fee for performance of Vault (given to `rewards`)
performanceFee: public(uint256)
MAX_BPS: constant(uint256) = 10_000 # 100%, or 10k basis points
# NOTE: A four-century period will be missing 3 of its 100 Julian leap years, leaving 97.
# So the average year has 365 + 97/400 = 365.2425 days
# ERROR(Julian): -0.0078
# ERROR(Gregorian): -0.0003
SECS_PER_YEAR: constant(uint256) = 31_556_952 # 365.2425 days
# `nonces` track `permit` approvals with signature.
nonces: public(HashMap[address, uint256])
DOMAIN_SEPARATOR: public(bytes32)
DOMAIN_TYPE_HASH: constant(bytes32) = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
PERMIT_TYPE_HASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
@external
def initialize(
token: address,
governance: address,
rewards: address,
nameOverride: String[64],
symbolOverride: String[32],
guardian: address = msg.sender,
management: address = msg.sender,
):
"""
@notice
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.
@dev
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.
@param token The token that may be deposited into this Vault.
@param governance The address authorized for governance interactions.
@param rewards The address to distribute rewards to.
@param management The address of the vault manager.
@param nameOverride Specify a custom Vault name. Leave empty for default choice.
@param symbolOverride Specify a custom Vault symbol name. Leave empty for default choice.
@param guardian The address authorized for guardian interactions. Defaults to caller.
"""
assert self.activation == 0 # dev: no devops199
self.token = ERC20(token)
if nameOverride == "":
self.name = concat(DetailedERC20(token).symbol(), " yVault")
else:
self.name = nameOverride
if symbolOverride == "":
self.symbol = concat("yv", DetailedERC20(token).symbol())
else:
self.symbol = symbolOverride
decimals: uint256 = DetailedERC20(token).decimals()
self.decimals = decimals
assert decimals < 256 # dev: see VVE-2020-0001
self.governance = governance
log UpdateGovernance(governance)
self.management = management
log UpdateManagement(management)
self.rewards = rewards
log UpdateRewards(rewards)
self.guardian = guardian
log UpdateGuardian(guardian)
self.performanceFee = 1000 # 10% of yield (per Strategy)
log UpdatePerformanceFee(convert(1000, uint256))
self.managementFee = 200 # 2% per year
log UpdateManagementFee(convert(200, uint256))
self.lastReport = block.timestamp
self.activation = block.timestamp
self.lockedProfitDegradation = convert(DEGRADATION_COEFFICIENT * 46 / 10 ** 6 , uint256) # 6 hours in blocks
# EIP-712
self.DOMAIN_SEPARATOR = keccak256(
concat(
DOMAIN_TYPE_HASH,
keccak256(convert("Yearn Vault", Bytes[11])),
keccak256(convert(API_VERSION, Bytes[28])),
convert(chain.id, bytes32),
convert(self, bytes32)
)
)
@pure
@external
def apiVersion() -> String[28]:
"""
@notice
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.
@dev
All strategies must have an `apiVersion()` that matches the Vault's
`API_VERSION`.
@return API_VERSION which holds the current version of this contract.
"""
return API_VERSION
@external
def setName(name: String[42]):
"""
@notice
Used to change the value of `name`.
This may only be called by governance.
@param name The new name to use.
"""
assert msg.sender == self.governance
self.name = name
@external
def setSymbol(symbol: String[20]):
"""
@notice
Used to change the value of `symbol`.
This may only be called by governance.
@param symbol The new symbol to use.
"""
assert msg.sender == self.governance
self.symbol = symbol
# 2-phase commit for a change in governance
@external
def setGovernance(governance: address):
"""
@notice
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.
@param governance The address requested to take over Vault governance.
"""
assert msg.sender == self.governance
self.pendingGovernance = governance
@external
def acceptGovernance():
"""
@notice
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.
@dev
setGovernance() should be called by the existing governance address,
prior to calling this function.
"""
assert msg.sender == self.pendingGovernance
self.governance = msg.sender
log UpdateGovernance(msg.sender)
@external
def setManagement(management: address):
"""
@notice
Changes the management address.
Management is able to make some investment decisions adjusting parameters.
This may only be called by governance.
@param management The address to use for managing.
"""
assert msg.sender == self.governance
self.management = management
log UpdateManagement(management)
@external
def setRewards(rewards: address):
"""
@notice
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.
@param rewards The address to use for collecting rewards.
"""
assert msg.sender == self.governance
assert not (rewards in [self, ZERO_ADDRESS])
self.rewards = rewards
log UpdateRewards(rewards)
@external
def setLockedProfitDegradation(degradation: uint256):
"""
@notice
Changes the locked profit degradation.
@param degradation The rate of degradation in percent per second scaled to 1e18.
"""
assert msg.sender == self.governance
# Since "degradation" is of type uint256 it can never be less than zero
assert degradation <= DEGRADATION_COEFFICIENT
self.lockedProfitDegradation = degradation
@external
def setDepositLimit(limit: uint256):
"""
@notice
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.
@param limit The new deposit limit to use.
"""
assert msg.sender == self.governance
self.depositLimit = limit
log UpdateDepositLimit(limit)
@external
def setPerformanceFee(fee: uint256):
"""
@notice
Used to change the value of `performanceFee`.
Should set this value below the maximum strategist performance fee.
This may only be called by governance.
@param fee The new performance fee to use.
"""
assert msg.sender == self.governance
assert fee <= MAX_BPS / 2
self.performanceFee = fee
log UpdatePerformanceFee(fee)
@external
def setManagementFee(fee: uint256):
"""
@notice
Used to change the value of `managementFee`.
This may only be called by governance.
@param fee The new management fee to use.
"""
assert msg.sender == self.governance
assert fee <= MAX_BPS
self.managementFee = fee
log UpdateManagementFee(fee)
@external
def setGuardian(guardian: address):
"""
@notice
Used to change the address of `guardian`.
This may only be called by governance or the existing guardian.
@param guardian The new guardian address to use.
"""
assert msg.sender in [self.guardian, self.governance]
self.guardian = guardian
log UpdateGuardian(guardian)
@external
def setEmergencyShutdown(active: bool):
"""
@notice
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.
@param active
If true, the Vault goes into Emergency Shutdown. If false, the Vault
goes back into Normal Operation.
"""
if active:
assert msg.sender in [self.guardian, self.governance]
else:
assert msg.sender == self.governance
self.emergencyShutdown = active
log EmergencyShutdown(active)
@external
def setWithdrawalQueue(queue: address[MAXIMUM_STRATEGIES]):
"""
@notice
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.
@dev
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.
@param queue
The array of addresses to use as the new withdrawal queue. This is
order sensitive.
"""
assert msg.sender in [self.management, self.governance]
# HACK: Temporary until Vyper adds support for Dynamic arrays
old_queue: address[MAXIMUM_STRATEGIES] = empty(address[MAXIMUM_STRATEGIES])
for i in range(MAXIMUM_STRATEGIES):
old_queue[i] = self.withdrawalQueue[i]
if queue[i] == ZERO_ADDRESS:
# NOTE: Cannot use this method to remove entries from the queue
assert old_queue[i] == ZERO_ADDRESS
break
# NOTE: Cannot use this method to add more entries to the queue
assert old_queue[i] != ZERO_ADDRESS
assert self.strategies[queue[i]].activation > 0
existsInOldQueue: bool = False
for j in range(MAXIMUM_STRATEGIES):
if queue[j] == ZERO_ADDRESS:
existsInOldQueue = True
break
if queue[i] == old_queue[j]:
# NOTE: Ensure that every entry in queue prior to reordering exists now
existsInOldQueue = True
if j <= i:
# NOTE: This will only check for duplicate entries in queue after `i`
continue
assert queue[i] != queue[j] # dev: do not add duplicate strategies
assert existsInOldQueue # dev: do not add new strategies
self.withdrawalQueue[i] = queue[i]
log UpdateWithdrawalQueue(queue)
@internal
def erc20_safe_transfer(token: address, receiver: address, amount: uint256):
# Used only to send tokens that are not the type managed by this Vault.
# HACK: Used to handle non-compliant tokens like USDT
response: Bytes[32] = raw_call(
token,
concat(
method_id("transfer(address,uint256)"),
convert(receiver, bytes32),
convert(amount, bytes32),
),
max_outsize=32,
)
if len(response) > 0:
assert convert(response, bool), "Transfer failed!"
@internal
def erc20_safe_transferFrom(token: address, sender: address, receiver: address, amount: uint256):
# Used only to send tokens that are not the type managed by this Vault.
# HACK: Used to handle non-compliant tokens like USDT
response: Bytes[32] = raw_call(
token,
concat(
method_id("transferFrom(address,address,uint256)"),
convert(sender, bytes32),
convert(receiver, bytes32),
convert(amount, bytes32),
),
max_outsize=32,
)
if len(response) > 0:
assert convert(response, bool), "Transfer failed!"
@internal
def _transfer(sender: address, receiver: address, amount: uint256):
# See note on `transfer()`.
# Protect people from accidentally sending their shares to bad places
assert receiver not in [self, ZERO_ADDRESS]
self.balanceOf[sender] -= amount
self.balanceOf[receiver] += amount
log Transfer(sender, receiver, amount)
@external
def transfer(receiver: address, amount: uint256) -> bool:
"""
@notice
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.
@param receiver
The address shares are being transferred to. Must not be this contract's
address, must not be 0x0.
@param amount The quantity of shares to transfer.
@return
True if transfer is sent to an address other than this contract's or
0x0, otherwise the transaction will fail.
"""
self._transfer(msg.sender, receiver, amount)
return True
@external
def transferFrom(sender: address, receiver: address, amount: uint256) -> bool:
"""
@notice
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`.
@param sender The address shares are being transferred from.
@param receiver
The address shares are being transferred to. Must not be this contract's
address, must not be 0x0.
@param amount The quantity of shares to transfer.
@return
True if transfer is sent to an address other than this contract's or
0x0, otherwise the transaction will fail.
"""
# Unlimited approval (saves an SSTORE)
if (self.allowance[sender][msg.sender] < MAX_UINT256):
allowance: uint256 = self.allowance[sender][msg.sender] - amount
self.allowance[sender][msg.sender] = allowance
# NOTE: Allows log filters to have a full accounting of allowance changes
log Approval(sender, msg.sender, allowance)
self._transfer(sender, receiver, amount)
return True
@external
def approve(spender: address, amount: uint256) -> bool:
"""
@dev 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
@param spender The address which will spend the funds.
@param amount The amount of tokens to be spent.
"""
self.allowance[msg.sender][spender] = amount
log Approval(msg.sender, spender, amount)
return True
@external
def increaseAllowance(spender: address, amount: uint256) -> bool:
"""
@dev 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
@param spender The address which will spend the funds.
@param amount The amount of tokens to increase the allowance by.
"""
self.allowance[msg.sender][spender] += amount
log Approval(msg.sender, spender, self.allowance[msg.sender][spender])
return True
@external
def decreaseAllowance(spender: address, amount: uint256) -> bool:
"""
@dev 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
@param spender The address which will spend the funds.
@param amount The amount of tokens to decrease the allowance by.
"""
self.allowance[msg.sender][spender] -= amount
log Approval(msg.sender, spender, self.allowance[msg.sender][spender])
return True
@external
def permit(owner: address, spender: address, amount: uint256, expiry: uint256, signature: Bytes[65]) -> bool:
"""
@notice
Approves spender by owner's signature to expend owner's tokens.
See https://eips.ethereum.org/EIPS/eip-2612.
@param owner The address which is a source of funds and has signed the Permit.
@param spender The address which is allowed to spend the funds.
@param amount The amount of tokens to be spent.
@param expiry The timestamp after which the Permit is no longer valid.
@param signature A valid secp256k1 signature of Permit by owner encoded as r, s, v.
@return True, if transaction completes successfully
"""
assert owner != ZERO_ADDRESS # dev: invalid owner
assert expiry == 0 or expiry >= block.timestamp # dev: permit expired
nonce: uint256 = self.nonces[owner]
digest: bytes32 = keccak256(
concat(
b'\x19\x01',
self.DOMAIN_SEPARATOR,
keccak256(
concat(
PERMIT_TYPE_HASH,
convert(owner, bytes32),
convert(spender, bytes32),
convert(amount, bytes32),
convert(nonce, bytes32),
convert(expiry, bytes32),
)
)
)
)
# NOTE: signature is packed as r, s, v
r: uint256 = convert(slice(signature, 0, 32), uint256)
s: uint256 = convert(slice(signature, 32, 32), uint256)
v: uint256 = convert(slice(signature, 64, 1), uint256)
assert ecrecover(digest, v, r, s) == owner # dev: invalid signature
self.allowance[owner][spender] = amount
self.nonces[owner] = nonce + 1
log Approval(owner, spender, amount)
return True
@view
@internal
def _totalAssets() -> uint256:
# See note on `totalAssets()`.
return self.token.balanceOf(self) + self.totalDebt
@view
@external
def totalAssets() -> uint256:
"""
@notice
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 The total assets under control of this Vault.
"""
return self._totalAssets()
@view
@internal
def _calculateLockedProfit() -> uint256:
lockedFundsRatio: uint256 = (block.timestamp - self.lastReport) * self.lockedProfitDegradation
if(lockedFundsRatio < DEGRADATION_COEFFICIENT):
lockedProfit: uint256 = self.lockedProfit
return lockedProfit - (
lockedFundsRatio
* lockedProfit
/ DEGRADATION_COEFFICIENT
)
else:
return 0
@internal
def _issueSharesForAmount(to: address, amount: uint256) -> uint256:
# Issues `amount` Vault shares to `to`.
# Shares must be issued prior to taking on new collateral, or
# calculation will be wrong. This means that only *trusted* tokens
# (with no capability for exploitative behavior) can be used.
shares: uint256 = 0
# HACK: Saves 2 SLOADs (~200 gas, post-Berlin)
totalSupply: uint256 = self.totalSupply
if totalSupply > 0:
# Mint amount of shares based on what the Vault is managing overall
# NOTE: if sqrt(token.totalSupply()) > 1e39, this could potentially revert
freeFunds: uint256 = self._totalAssets() - self._calculateLockedProfit()
shares = amount * totalSupply / freeFunds # dev: no free funds
else:
# No existing shares, so mint 1:1
shares = amount
assert shares != 0 # dev: division rounding resulted in zero
# Mint new shares
self.totalSupply = totalSupply + shares
self.balanceOf[to] += shares
log Transfer(ZERO_ADDRESS, to, shares)
return shares
@external
@nonreentrant("withdraw")
def deposit(_amount: uint256 = MAX_UINT256, recipient: address = msg.sender) -> uint256:
"""
@notice
Deposits `_amount` `token`, issuing shares to `recipient`. If the
Vault is in Emergency Shutdown, deposits will not be accepted and this
call will fail.
@dev
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".
@param _amount The quantity of tokens to deposit, defaults to all.
@param recipient
The address to issue the shares in this Vault to. Defaults to the
caller's address.
@return The issued Vault shares.
"""
assert not self.emergencyShutdown # Deposits are locked out
assert recipient not in [self, ZERO_ADDRESS]
amount: uint256 = _amount
# If _amount not specified, transfer the full token balance,
# up to deposit limit
if amount == MAX_UINT256:
amount = min(
self.depositLimit - self._totalAssets(),
self.token.balanceOf(msg.sender),
)
else:
# Ensure deposit limit is respected
assert self._totalAssets() + amount <= self.depositLimit
# Ensure we are depositing something
assert amount > 0
# Issue new shares (needs to be done before taking deposit to be accurate)
# Shares are issued to recipient (may be different from msg.sender)
# See @dev note, above.
shares: uint256 = self._issueSharesForAmount(recipient, amount)
# Tokens are transferred from msg.sender (may be different from _recipient)
self.erc20_safe_transferFrom(self.token.address, msg.sender, self, amount)
return shares # Just in case someone wants them
@view
@internal
def _shareValue(shares: uint256) -> uint256:
# Returns price = 1:1 if vault is empty
if self.totalSupply == 0:
return shares
# Determines the current value of `shares`.
# NOTE: if sqrt(Vault.totalAssets()) >>> 1e39, this could potentially revert
freeFunds: uint256 = self._totalAssets() - self._calculateLockedProfit()
return (
shares
* freeFunds
/ self.totalSupply
)
@view
@internal
def _sharesForAmount(amount: uint256) -> uint256:
# Determines how many shares `amount` of token would receive.
# See dev note on `deposit`.
if self._totalAssets() > 0:
# NOTE: if sqrt(token.totalSupply()) > 1e37, this could potentially revert
return (
amount
* self.totalSupply
/ self._totalAssets()
)
else:
return 0
@view
@external
def maxAvailableShares() -> uint256:
"""
@notice
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.
@dev
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 The total quantity of shares this Vault can provide.
"""
shares: uint256 = self._sharesForAmount(self.token.balanceOf(self))
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break
shares += self._sharesForAmount(self.strategies[strategy].totalDebt)
return shares
@internal
def _reportLoss(strategy: address, loss: uint256):
# Loss can only be up the amount of debt issued to strategy
totalDebt: uint256 = self.strategies[strategy].totalDebt
assert totalDebt >= loss
# Also, make sure we reduce our trust with the strategy by the amount of loss
if self.debtRatio != 0: # if vault with single strategy that is set to EmergencyOne
# NOTE: The context to this calculation is different than the calculation in `_reportLoss`,
# this calculation intentionally approximates via `totalDebt` to avoid manipulatable results
ratio_change: uint256 = min(
# NOTE: This calculation isn't 100% precise, the adjustment is ~10%-20% more severe due to EVM math
loss * self.debtRatio / self.totalDebt,
self.strategies[strategy].debtRatio,
)
self.strategies[strategy].debtRatio -= ratio_change
self.debtRatio -= ratio_change
# Finally, adjust our strategy's parameters by the loss
self.strategies[strategy].totalLoss += loss
self.strategies[strategy].totalDebt = totalDebt - loss
self.totalDebt -= loss
@external
@nonreentrant("withdraw")
def withdraw(
maxShares: uint256 = MAX_UINT256,
recipient: address = msg.sender,
maxLoss: uint256 = 1, # 0.01% [BPS]
) -> uint256:
"""
@notice
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.
@dev
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.
@param maxShares
How many shares to try and redeem for tokens, defaults to all.
@param recipient
The address to issue the shares in this Vault to. Defaults to the
caller's address.
@param maxLoss
The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%.
@return The quantity of tokens redeemed for `_shares`.
"""
shares: uint256 = maxShares # May reduce this number below
# Max Loss is <=100%, revert otherwise
assert maxLoss <= MAX_BPS
# If _shares not specified, transfer full share balance
if shares == MAX_UINT256:
shares = self.balanceOf[msg.sender]
# Limit to only the shares they own
assert shares <= self.balanceOf[msg.sender]
# Ensure we are withdrawing something
assert shares > 0
# See @dev note, above.
value: uint256 = self._shareValue(shares)
totalLoss: uint256 = 0
if value > self.token.balanceOf(self):
# We need to go get some from our strategies in the withdrawal queue
# NOTE: This performs forced withdrawals from each Strategy. During
# forced withdrawal, a Strategy may realize a loss. That loss
# is reported back to the Vault, and the will affect the amount
# of tokens that the withdrawer receives for their shares. They
# can optionally specify the maximum acceptable loss (in BPS)
# to prevent excessive losses on their withdrawals (which may
# happen in certain edge cases where Strategies realize a loss)
for strategy in self.withdrawalQueue:
if strategy == ZERO_ADDRESS:
break # We've exhausted the queue
vault_balance: uint256 = self.token.balanceOf(self)
if value <= vault_balance:
break # We're done withdrawing
amountNeeded: uint256 = value - vault_balance
# NOTE: Don't withdraw more than the debt so that Strategy can still
# continue to work based on the profits it has
# NOTE: This means that user will lose out on any profits that each
# Strategy in the queue would return on next harvest, benefiting others
amountNeeded = min(amountNeeded, self.strategies[strategy].totalDebt)
if amountNeeded == 0:
continue # Nothing to withdraw from this Strategy, try the next one
# Force withdraw amount from each Strategy in the order set by governance
loss: uint256 = Strategy(strategy).withdraw(amountNeeded)
withdrawn: uint256 = self.token.balanceOf(self) - vault_balance
# NOTE: Withdrawer incurs any losses from liquidation
if loss > 0:
value -= loss
totalLoss += loss
self._reportLoss(strategy, loss)
# Reduce the Strategy's debt by the amount withdrawn ("realized returns")
# NOTE: This doesn't add to returns as it's not earned by "normal means"
self.strategies[strategy].totalDebt -= withdrawn
self.totalDebt -= withdrawn
# NOTE: We have withdrawn everything possible out of the withdrawal queue
# but we still don't have enough to fully pay them back, so adjust
# to the total amount we've freed up through forced withdrawals
vault_balance: uint256 = self.token.balanceOf(self)
if value > vault_balance:
value = vault_balance
# NOTE: Burn # of shares that corresponds to what Vault has on-hand,
# including the losses that were incurred above during withdrawals
shares = self._sharesForAmount(value + totalLoss)
# NOTE: This loss protection is put in place to revert if losses from
# withdrawing are more than what is considered acceptable.
assert totalLoss <= maxLoss * (value + totalLoss) / MAX_BPS
# Burn shares (full value of what is being withdrawn)
self.totalSupply -= shares
self.balanceOf[msg.sender] -= shares
log Transfer(msg.sender, ZERO_ADDRESS, shares)
# Withdraw remaining balance to _recipient (may be different to msg.sender) (minus fee)
self.erc20_safe_transfer(self.token.address, recipient, value)
return value
@view
@external
def pricePerShare() -> uint256:
"""
@notice Gives the price for a single Vault share.
@dev See dev note on `withdraw`.
@return The value of a single share.
"""
return self._shareValue(10 ** self.decimals)
@internal
def _organizeWithdrawalQueue():
# Reorganize `withdrawalQueue` based on premise that if there is an
# empty value between two actual values, then the empty value should be
# replaced by the later value.
# NOTE: Relative ordering of non-zero values is maintained.
offset: uint256 = 0
for idx in range(MAXIMUM_STRATEGIES):
strategy: address = self.withdrawalQueue[idx]
if strategy == ZERO_ADDRESS:
offset += 1 # how many values we need to shift, always `<= idx`
elif offset > 0:
self.withdrawalQueue[idx - offset] = strategy
self.withdrawalQueue[idx] = ZERO_ADDRESS
@external
def addStrategy(
strategy: address,
debtRatio: uint256,
minDebtPerHarvest: uint256,
maxDebtPerHarvest: uint256,
performanceFee: uint256,
):
"""
@notice
Add a Strategy to the Vault.
This may only be called by governance.
@dev
The Strategy will be appended to `withdrawalQueue`, call
`setWithdrawalQueue` to change the order.
@param strategy The address of the Strategy to add.
@param debtRatio
The share of the total assets in the `vault that the `strategy` has access to.
@param minDebtPerHarvest
Lower limit on the increase of debt since last harvest
@param maxDebtPerHarvest
Upper limit on the increase of debt since last harvest
@param performanceFee
The fee the strategist will receive based on this Vault's performance.
"""
# Check if queue is full
assert self.withdrawalQueue[MAXIMUM_STRATEGIES - 1] == ZERO_ADDRESS
# Check calling conditions
assert not self.emergencyShutdown
assert msg.sender == self.governance
# Check strategy configuration
assert strategy != ZERO_ADDRESS
assert self.strategies[strategy].activation == 0
assert self == Strategy(strategy).vault()
assert self.token.address == Strategy(strategy).want()
# Check strategy parameters
assert self.debtRatio + debtRatio <= MAX_BPS
assert minDebtPerHarvest <= maxDebtPerHarvest
assert performanceFee <= MAX_BPS / 2
# Add strategy to approved strategies
self.strategies[strategy] = StrategyParams({
performanceFee: performanceFee,
activation: block.timestamp,
debtRatio: debtRatio,
minDebtPerHarvest: minDebtPerHarvest,
maxDebtPerHarvest: maxDebtPerHarvest,
lastReport: block.timestamp,
totalDebt: 0,
totalGain: 0,
totalLoss: 0,
})
log StrategyAdded(strategy, debtRatio, minDebtPerHarvest, maxDebtPerHarvest, performanceFee)
# Update Vault parameters
self.debtRatio += debtRatio
# Add strategy to the end of the withdrawal queue
self.withdrawalQueue[MAXIMUM_STRATEGIES - 1] = strategy
self._organizeWithdrawalQueue()
@external
def updateStrategyDebtRatio(
strategy: address,
debtRatio: uint256,
):
"""
@notice
Change the quantity of assets `strategy` may manage.
This may be called by governance or management.
@param strategy The Strategy to update.
@param debtRatio The quantity of assets `strategy` may now manage.
"""
assert msg.sender in [self.management, self.governance]
assert self.strategies[strategy].activation > 0
self.debtRatio -= self.strategies[strategy].debtRatio
self.strategies[strategy].debtRatio = debtRatio
self.debtRatio += debtRatio
assert self.debtRatio <= MAX_BPS
log StrategyUpdateDebtRatio(strategy, debtRatio)
@external
def updateStrategyMinDebtPerHarvest(
strategy: address,
minDebtPerHarvest: uint256,
):
"""
@notice
Change the quantity assets per block this Vault may deposit to or
withdraw from `strategy`.
This may only be called by governance or management.
@param strategy The Strategy to update.
@param minDebtPerHarvest
Lower limit on the increase of debt since last harvest
"""
assert msg.sender in [self.management, self.governance]
assert self.strategies[strategy].activation > 0
assert self.strategies[strategy].maxDebtPerHarvest >= minDebtPerHarvest
self.strategies[strategy].minDebtPerHarvest = minDebtPerHarvest
log StrategyUpdateMinDebtPerHarvest(strategy, minDebtPerHarvest)
@external
def updateStrategyMaxDebtPerHarvest(
strategy: address,
maxDebtPerHarvest: uint256,
):
"""
@notice
Change the quantity assets per block this Vault may deposit to or
withdraw from `strategy`.
This may only be called by governance or management.
@param strategy The Strategy to update.
@param maxDebtPerHarvest
Upper limit on the increase of debt since last harvest
"""
assert msg.sender in [self.management, self.governance]
assert self.strategies[strategy].activation > 0
assert self.strategies[strategy].minDebtPerHarvest <= maxDebtPerHarvest
self.strategies[strategy].maxDebtPerHarvest = maxDebtPerHarvest
log StrategyUpdateMaxDebtPerHarvest(strategy, maxDebtPerHarvest)
@external
def updateStrategyPerformanceFee(
strategy: address,
performanceFee: uint256,
):
"""
@notice
Change the fee the strategist will receive based on this Vault's
performance.
This may only be called by governance.
@param strategy The Strategy to update.
@param performanceFee The new fee the strategist will receive.
"""
assert msg.sender == self.governance
assert performanceFee <= MAX_BPS / 2
assert self.strategies[strategy].activation > 0
self.strategies[strategy].performanceFee = performanceFee
log StrategyUpdatePerformanceFee(strategy, performanceFee)
@internal
def _revokeStrategy(strategy: address):
self.debtRatio -= self.strategies[strategy].debtRatio
self.strategies[strategy].debtRatio = 0
log StrategyRevoked(strategy)
@external
def migrateStrategy(oldVersion: address, newVersion: address):
"""
@notice
Migrates a Strategy, including all assets from `oldVersion` to
`newVersion`.
This may only be called by governance.
@dev
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.
@param oldVersion The existing Strategy to migrate from.
@param newVersion The new Strategy to migrate to.
"""
assert msg.sender == self.governance
assert newVersion != ZERO_ADDRESS
assert self.strategies[oldVersion].activation > 0
assert self.strategies[newVersion].activation == 0
strategy: StrategyParams = self.strategies[oldVersion]
self._revokeStrategy(oldVersion)
# _revokeStrategy will lower the debtRatio
self.debtRatio += strategy.debtRatio
# Debt is migrated to new strategy
self.strategies[oldVersion].totalDebt = 0
self.strategies[newVersion] = StrategyParams({
performanceFee: strategy.performanceFee,
# NOTE: use last report for activation time, so E[R] calc works
activation: strategy.lastReport,
debtRatio: strategy.debtRatio,
minDebtPerHarvest: strategy.minDebtPerHarvest,
maxDebtPerHarvest: strategy.maxDebtPerHarvest,
lastReport: strategy.lastReport,
totalDebt: strategy.totalDebt,
totalGain: 0,
totalLoss: 0,
})
Strategy(oldVersion).migrate(newVersion)
log StrategyMigrated(oldVersion, newVersion)
for idx in range(MAXIMUM_STRATEGIES):
if self.withdrawalQueue[idx] == oldVersion:
self.withdrawalQueue[idx] = newVersion
return # Don't need to reorder anything because we swapped
@external
def revokeStrategy(strategy: address = msg.sender):
"""
@notice
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.
@param strategy The Strategy to revoke.
"""
assert msg.sender in [strategy, self.governance, self.guardian]
assert self.strategies[strategy].debtRatio != 0 # dev: already zero
self._revokeStrategy(strategy)
@external
def addStrategyToQueue(strategy: address):
"""
@notice
Adds `strategy` to `withdrawalQueue`.
This may only be called by governance or management.
@dev
The Strategy will be appended to `withdrawalQueue`, call
`setWithdrawalQueue` to change the order.
@param strategy The Strategy to add.
"""
assert msg.sender in [self.management, self.governance]
# Must be a current Strategy
assert self.strategies[strategy].activation > 0
# Can't already be in the queue
last_idx: uint256 = 0
for s in self.withdrawalQueue:
if s == ZERO_ADDRESS:
break
assert s != strategy
last_idx += 1
# Check if queue is full
assert last_idx < MAXIMUM_STRATEGIES
self.withdrawalQueue[MAXIMUM_STRATEGIES - 1] = strategy
self._organizeWithdrawalQueue()
log StrategyAddedToQueue(strategy)
@external
def removeStrategyFromQueue(strategy: address):
"""
@notice
Remove `strategy` from `withdrawalQueue`.
This may only be called by governance or management.
@dev
We don't do this with revokeStrategy because it should still
be possible to withdraw from the Strategy if it's unwinding.
@param strategy The Strategy to remove.
"""
assert msg.sender in [self.management, self.governance]
for idx in range(MAXIMUM_STRATEGIES):
if self.withdrawalQueue[idx] == strategy:
self.withdrawalQueue[idx] = ZERO_ADDRESS
self._organizeWithdrawalQueue()
log StrategyRemovedFromQueue(strategy)
return # We found the right location and cleared it
raise # We didn't find the Strategy in the queue
@view
@internal
def _debtOutstanding(strategy: address) -> uint256:
# See note on `debtOutstanding()`.
if self.debtRatio == 0:
return self.strategies[strategy].totalDebt
strategy_debtLimit: uint256 = (
self.strategies[strategy].debtRatio
* self._totalAssets()
/ MAX_BPS
)
strategy_totalDebt: uint256 = self.strategies[strategy].totalDebt
if self.emergencyShutdown:
return strategy_totalDebt
elif strategy_totalDebt <= strategy_debtLimit:
return 0
else:
return strategy_totalDebt - strategy_debtLimit
@view
@external
def debtOutstanding(strategy: address = msg.sender) -> uint256:
"""
@notice
Determines if `strategy` is past its debt limit and if any tokens
should be withdrawn to the Vault.
@param strategy The Strategy to check. Defaults to the caller.
@return The quantity of tokens to withdraw.
"""
return self._debtOutstanding(strategy)
@view
@internal
def _creditAvailable(strategy: address) -> uint256:
# See note on `creditAvailable()`.
if self.emergencyShutdown:
return 0
vault_totalAssets: uint256 = self._totalAssets()
vault_debtLimit: uint256 = self.debtRatio * vault_totalAssets / MAX_BPS
vault_totalDebt: uint256 = self.totalDebt
strategy_debtLimit: uint256 = self.strategies[strategy].debtRatio * vault_totalAssets / MAX_BPS
strategy_totalDebt: uint256 = self.strategies[strategy].totalDebt
strategy_minDebtPerHarvest: uint256 = self.strategies[strategy].minDebtPerHarvest
strategy_maxDebtPerHarvest: uint256 = self.strategies[strategy].maxDebtPerHarvest
# Exhausted credit line
if strategy_debtLimit <= strategy_totalDebt or vault_debtLimit <= vault_totalDebt:
return 0
# Start with debt limit left for the Strategy
available: uint256 = strategy_debtLimit - strategy_totalDebt
# Adjust by the global debt limit left
available = min(available, vault_debtLimit - vault_totalDebt)
# Can only borrow up to what the contract has in reserve
# NOTE: Running near 100% is discouraged
available = min(available, self.token.balanceOf(self))
# Adjust by min and max borrow limits (per harvest)
# NOTE: min increase can be used to ensure that if a strategy has a minimum
# amount of capital needed to purchase a position, it's not given capital
# it can't make use of yet.
# NOTE: max increase is used to make sure each harvest isn't bigger than what
# is authorized. This combined with adjusting min and max periods in
# `BaseStrategy` can be used to effect a "rate limit" on capital increase.
if available < strategy_minDebtPerHarvest:
return 0
else:
return min(available, strategy_maxDebtPerHarvest)
@view
@external
def creditAvailable(strategy: address = msg.sender) -> uint256:
"""
@notice
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.
@param strategy The Strategy to check. Defaults to caller.
@return The quantity of tokens available for the Strategy to draw on.
"""
return self._creditAvailable(strategy)
@view
@internal
def _expectedReturn(strategy: address) -> uint256:
# See note on `expectedReturn()`.
strategy_lastReport: uint256 = self.strategies[strategy].lastReport
timeSinceLastHarvest: uint256 = block.timestamp - strategy_lastReport
totalHarvestTime: uint256 = strategy_lastReport - self.strategies[strategy].activation
# NOTE: If either `timeSinceLastHarvest` or `totalHarvestTime` is 0, we can short-circuit to `0`
if timeSinceLastHarvest > 0 and totalHarvestTime > 0 and Strategy(strategy).isActive():
# NOTE: Unlikely to throw unless strategy accumalates >1e68 returns
# NOTE: Calculate average over period of time where harvests have occured in the past
return (
self.strategies[strategy].totalGain
* timeSinceLastHarvest
/ totalHarvestTime
)
else:
return 0 # Covers the scenario when block.timestamp == activation
@view
@external
def availableDepositLimit() -> uint256:
if self.depositLimit > self._totalAssets():
return self.depositLimit - self._totalAssets()
else:
return 0
@view
@external
def expectedReturn(strategy: address = msg.sender) -> uint256:
"""
@notice
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).
@param strategy The Strategy to determine the expected return for. Defaults to caller.
@return
The anticipated amount `strategy` should make on its investment
since its last report.
"""
return self._expectedReturn(strategy)
@internal
def _assessFees(strategy: address, gain: uint256) -> uint256:
# Issue new shares to cover fees
# NOTE: In effect, this reduces overall share price by the combined fee
# NOTE: may throw if Vault.totalAssets() > 1e64, or not called for more than a year
duration: uint256 = block.timestamp - self.strategies[strategy].lastReport
assert duration != 0 # can't assessFees twice within the same block
if gain == 0:
# NOTE: The fees are not charged if there hasn't been any gains reported
return 0
management_fee: uint256 = (
(
(self.strategies[strategy].totalDebt - Strategy(strategy).delegatedAssets())
* duration
* self.managementFee
)
/ MAX_BPS
/ SECS_PER_YEAR
)
# NOTE: Applies if Strategy is not shutting down, or it is but all debt paid off
# NOTE: No fee is taken when a Strategy is unwinding it's position, until all debt is paid
strategist_fee: uint256 = (
gain
* self.strategies[strategy].performanceFee
/ MAX_BPS
)
# NOTE: Unlikely to throw unless strategy reports >1e72 harvest profit
performance_fee: uint256 = gain * self.performanceFee / MAX_BPS
# NOTE: This must be called prior to taking new collateral,
# or the calculation will be wrong!
# NOTE: This must be done at the same time, to ensure the relative
# ratio of governance_fee : strategist_fee is kept intact
total_fee: uint256 = performance_fee + strategist_fee + management_fee
# ensure total_fee is not more than gain
if total_fee > gain:
total_fee = gain
if total_fee > 0: # NOTE: If mgmt fee is 0% and no gains were realized, skip
reward: uint256 = self._issueSharesForAmount(self, total_fee)
# Send the rewards out as new shares in this Vault
if strategist_fee > 0: # NOTE: Guard against DIV/0 fault
# NOTE: Unlikely to throw unless sqrt(reward) >>> 1e39
strategist_reward: uint256 = (
strategist_fee
* reward
/ total_fee
)
self._transfer(self, strategy, strategist_reward)
# NOTE: Strategy distributes rewards at the end of harvest()
# NOTE: Governance earns any dust leftover from flooring math above
if self.balanceOf[self] > 0:
self._transfer(self, self.rewards, self.balanceOf[self])
return total_fee
@external
def report(gain: uint256, loss: uint256, _debtPayment: uint256) -> uint256:
"""
@notice
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.
@dev
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.
@param 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
@param 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.
@param _debtPayment
Amount Strategy has made available to cover outstanding debt
@return Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown).
"""
# Only approved strategies can call this function
assert self.strategies[msg.sender].activation > 0
# No lying about total available to withdraw!
assert self.token.balanceOf(msg.sender) >= gain + _debtPayment
# We have a loss to report, do it before the rest of the calculations
if loss > 0:
self._reportLoss(msg.sender, loss)
# Assess both management fee and performance fee, and issue both as shares of the vault
totalFees: uint256 = self._assessFees(msg.sender, gain)
# Returns are always "realized gains"
self.strategies[msg.sender].totalGain += gain
# Compute the line of credit the Vault is able to offer the Strategy (if any)
credit: uint256 = self._creditAvailable(msg.sender)
# Outstanding debt the Strategy wants to take back from the Vault (if any)
# NOTE: debtOutstanding <= StrategyParams.totalDebt
debt: uint256 = self._debtOutstanding(msg.sender)
debtPayment: uint256 = min(_debtPayment, debt)
if debtPayment > 0:
self.strategies[msg.sender].totalDebt -= debtPayment
self.totalDebt -= debtPayment
debt -= debtPayment
# NOTE: `debt` is being tracked for later
# Update the actual debt based on the full credit we are extending to the Strategy
# or the returns if we are taking funds back
# NOTE: credit + self.strategies[msg.sender].totalDebt is always < self.debtLimit
# NOTE: At least one of `credit` or `debt` is always 0 (both can be 0)
if credit > 0:
self.strategies[msg.sender].totalDebt += credit
self.totalDebt += credit
# Give/take balance to Strategy, based on the difference between the reported gains
# (if any), the debt payment (if any), the credit increase we are offering (if any),
# and the debt needed to be paid off (if any)
# NOTE: This is just used to adjust the balance of tokens between the Strategy and
# the Vault based on the Strategy's debt limit (as well as the Vault's).
totalAvail: uint256 = gain + debtPayment
if totalAvail < credit: # credit surplus, give to Strategy
self.erc20_safe_transfer(self.token.address, msg.sender, credit - totalAvail)
elif totalAvail > credit: # credit deficit, take from Strategy
self.erc20_safe_transferFrom(self.token.address, msg.sender, self, totalAvail - credit)
# else, don't do anything because it is balanced
# Profit is locked and gradually released per block
# NOTE: compute current locked profit and replace with sum of current and new
lockedProfitBeforeLoss: uint256 = self._calculateLockedProfit() + gain - totalFees
if lockedProfitBeforeLoss > loss:
self.lockedProfit = lockedProfitBeforeLoss - loss
else:
self.lockedProfit = 0
# Update reporting time
self.strategies[msg.sender].lastReport = block.timestamp
self.lastReport = block.timestamp
log StrategyReported(
msg.sender,
gain,
loss,
debtPayment,
self.strategies[msg.sender].totalGain,
self.strategies[msg.sender].totalLoss,
self.strategies[msg.sender].totalDebt,
credit,
self.strategies[msg.sender].debtRatio,
)
if self.strategies[msg.sender].debtRatio == 0 or self.emergencyShutdown:
# Take every last penny the Strategy has (Emergency Exit/revokeStrategy)
# NOTE: This is different than `debt` in order to extract *all* of the returns
return Strategy(msg.sender).estimatedTotalAssets()
else:
# Otherwise, just return what we have as debt outstanding
return debt
@external
def sweep(token: address, amount: uint256 = MAX_UINT256):
"""
@notice
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.
@param token The token to transfer out of this vault.
@param amount The quantity or tokenId to transfer out.
"""
assert msg.sender == self.governance
# Can't be used to steal what this Vault is protecting
assert token != self.token.address
value: uint256 = amount
if value == MAX_UINT256:
value = ERC20(token).balanceOf(self)
self.erc20_safe_transfer(token, self.governance, value)