Verified contractExactUnlicense
VaultV2InKind
Address0xd8fb90856ce7fa54b730e348ee3140b8af6da3c6
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- Unlicense
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,003,530
- Creation transaction
- 0xdf714b8b7e…74acc01eb4
23 files
- contracts/base/inkind/VaultV2InKind.solmain7.46 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol1.74 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol12.14 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.74 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol639 B
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol3.96 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol6.92 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.06 KB
- @openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol1.17 KB
- @openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol6.71 KB
- contracts/base/VaultStorage.sol8.84 KB
- contracts/base/VaultV1.sol13.04 KB
- contracts/base/VaultV2.sol3.56 KB
- contracts/base/inheritance/ControllableInit.sol799 B
- contracts/base/inheritance/GovernableInit.sol1.43 KB
- contracts/base/inheritance/Storage.sol875 B
- contracts/base/interface/IController.sol5.07 KB
- contracts/base/interface/IERC4626.sol14.4 KB
- contracts/base/interface/IInKindStrategy.sol754 B
- contracts/base/interface/IStrategy.sol1.37 KB
- contracts/base/interface/IUpgradeSource.sol200 B
- contracts/base/interface/IVault.sol1.93 KB
- contracts/base/upgradability/ReentrancyGuardUpgradeable.sol1.57 KB
contracts/base/inkind/VaultV2InKind.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "../VaultV2.sol";
import "../interface/IInKindStrategy.sol";
/**
* @title VaultV2InKind
* @dev `VaultV2` extended with governance-gated in-kind redemptions.
*
* While enabled, a holder can burn their vault shares and receive their pro-rata slice of
* the strategy's position tokens directly - the yield source's own ERC-20 shares - instead
* of the underlying asset. That gives them an exit when the yield source has no redeemable
* liquidity, alongside the normal withdrawal path, which keeps working throughout.
*
* The payout is a proportional split of the tokens actually held, so it never depends on
* the vault's cached share price. It does depend on the cached price NOT being stale in
* the other direction: minting at a stale price and immediately redeeming the true
* pro-rata slice would capture unaccrued yield from the holders who stay. So while the
* switch is on, every deposit and withdrawal syncs the strategy first and the ERC-4626
* views quote at that same synced rate, so previews match execution exactly.
*
* This is the plain-`VaultV2` flavour, for vaults that use neither the withdrawal hook nor
* the deposit cap. It is a drop-in implementation for an existing proxy: the switch lives
* in its own hashed slot, is off by default, and every inherited entrypoint is unchanged
* while it is off. Swapping the parent to `HookVaultV2` is all that a vault which does use
* those needs.
*/
contract VaultV2InKind is VaultV2 {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
/// @dev keccak256("eip1967.vaultStorage.redeemInKindEnabled") - 1. The same slot the
/// plain {VaultV2InKind} uses, so a vault can move between the two flavours.
bytes32 internal constant _REDEEM_IN_KIND_ENABLED_SLOT = 0xa1c4a46e26d435a0ab545346c100c3d90a738cc204528b23378616049e546b9f;
event RedeemInKind(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 shares,
uint256 assetsOut,
uint256 poolSharesOut
);
event RedeemInKindEnabled(bool enabled);
constructor() {
assert(_REDEEM_IN_KIND_ENABLED_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.redeemInKindEnabled")) - 1));
}
/**
* @notice Whether in-kind redemptions are currently enabled.
*/
function redeemInKindEnabled() public view returns (bool) {
return getBoolean(_REDEEM_IN_KIND_ENABLED_SLOT);
}
/**
* @notice Enables or disables in-kind redemptions. While enabled the strategy must
* implement {IInKindStrategy}, because deposits and withdrawals sync it first.
* @param _enabled New state of the in-kind redemption switch.
*/
function setRedeemInKindEnabled(bool _enabled) external onlyGovernance {
setBoolean(_REDEEM_IN_KIND_ENABLED_SLOT, _enabled);
emit RedeemInKindEnabled(_enabled);
}
/**
* @notice Burns `_owner`'s shares and pays `_receiver` their pro-rata slice of what the
* vault holds: the strategy's position tokens, plus a pro-rata part of any underlying
* sitting idle in the vault.
* @param _shares Number of vault shares to redeem.
* @param _receiver Address receiving the position tokens and underlying.
* @param _owner Address whose vault shares are burned.
* @return assetsOut Underlying transferred (pro-rata share of the vault's idle balance).
* @return poolSharesOut Position tokens transferred.
*/
function redeemInKind(
uint256 _shares,
address _receiver,
address _owner
) public nonReentrant defense whenStrategyDefined returns (uint256 assetsOut, uint256 poolSharesOut) {
require(redeemInKindEnabled(), "In-kind redemptions not enabled");
require(_shares > 0, "shares must be greater than 0");
require(_receiver != address(0), "receiver must be defined");
uint256 totalSupplyBefore = totalSupply();
require(totalSupplyBefore > 0, "Vault has no shares");
if (msg.sender != _owner) {
uint256 currentAllowance = allowance(_owner, msg.sender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= _shares, "ERC20: transfer amount exceeds allowance");
_approve(_owner, msg.sender, currentAllowance - _shares);
}
}
_burn(_owner, _shares);
assetsOut = underlyingBalanceInVault().mul(_shares).div(totalSupplyBefore);
poolSharesOut = IInKindStrategy(strategy()).withdrawInKind(_shares, totalSupplyBefore, _receiver);
require(assetsOut > 0 || poolSharesOut > 0, "nothing to redeem");
if (assetsOut > 0) {
IERC20Upgradeable(underlying()).safeTransfer(_receiver, assetsOut);
}
emit RedeemInKind(msg.sender, _receiver, _owner, _shares, assetsOut, poolSharesOut);
}
/**
* @notice Estimates the payout of {redeemInKind} for a given number of vault shares.
* @param _shares Number of vault shares to redeem.
* @return assetsOut Estimated underlying payout.
* @return poolSharesOut Estimated position-token payout.
*/
function previewRedeemInKind(uint256 _shares) public view returns (uint256 assetsOut, uint256 poolSharesOut) {
uint256 supply = totalSupply();
if (_shares == 0 || supply == 0 || strategy() == address(0)) {
return (0, 0);
}
assetsOut = underlyingBalanceInVault().mul(_shares).div(supply);
poolSharesOut = IInKindStrategy(strategy()).previewWithdrawInKind(_shares, supply);
}
/**
* @notice The position token paid out by {redeemInKind}.
*/
function inKindToken() public view returns (address) {
return IInKindStrategy(strategy()).rewardPool();
}
/**
* @dev Syncs the strategy's cached balance while in-kind redemptions are enabled, so
* deposits and withdrawals price at the live rate. A no-op while the switch is off,
* which is what keeps this a drop-in for a vault whose strategy has no hooks.
*/
function _syncStrategy() internal {
address _strategy = strategy();
if (redeemInKindEnabled() && _strategy != address(0)) {
IInKindStrategy(_strategy).syncBalance();
}
}
function _deposit(uint256 amount, address sender, address beneficiary) internal virtual override returns (uint256) {
_syncStrategy();
return super._deposit(amount, sender, beneficiary);
}
function _withdraw(uint256 numberOfShares, address receiver, address owner) internal virtual override returns (uint256) {
_syncStrategy();
return super._withdraw(numberOfShares, receiver, owner);
}
/**
* @notice Total assets under management. While in-kind redemptions are enabled this
* quotes at the live (synced) strategy balance, so previews match execution - which
* syncs before it prices.
* @return Total assets in the vault.
*/
function totalAssets() public view virtual override returns (uint256) {
address _strategy = strategy();
if (redeemInKindEnabled() && _strategy != address(0)) {
return underlyingBalanceInVault().add(IInKindStrategy(_strategy).syncedInvestedUnderlyingBalance());
}
return underlyingBalanceWithInvestment();
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable 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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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;
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");
(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");
(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");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
contracts/base/VaultStorage.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract VaultStorage is Initializable {
bytes32 internal constant _STRATEGY_SLOT = 0xf1a169aa0f736c2813818fdfbdc5755c31e0839c8f49831a16543496b28574ea;
bytes32 internal constant _UNDERLYING_SLOT = 0x1994607607e11d53306ef62e45e3bd85762c58d9bf38b5578bc4a258a26a7371;
bytes32 internal constant _UNDERLYING_UNIT_SLOT = 0xa66bc57d4b4eed7c7687876ca77997588987307cb13ecc23f5e52725192e5fff;
bytes32 internal constant _VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT = 0x39122c9adfb653455d0c05043bd52fcfbc2be864e832efd3abc72ce5a3d7ed5a;
bytes32 internal constant _VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT = 0x469a3bad2fab7b936c45eecd1f5da52af89cead3e2ed7f732b6f3fc92ed32308;
bytes32 internal constant _NEXT_IMPLEMENTATION_SLOT = 0xb1acf527cd7cd1668b30e5a9a1c0d845714604de29ce560150922c9d8c0937df;
bytes32 internal constant _NEXT_IMPLEMENTATION_TIMESTAMP_SLOT = 0x3bc747f4b148b37be485de3223c90b4468252967d2ea7f9fcbd8b6e653f434c9;
bytes32 internal constant _NEXT_STRATEGY_SLOT = 0xcd7bd9250b0e02f3b13eccf8c73ef5543cb618e0004628f9ca53b65fbdbde2d0;
bytes32 internal constant _NEXT_STRATEGY_TIMESTAMP_SLOT = 0x5d2b24811886ad126f78c499d71a932a5435795e4f2f6552f0900f12d663cdcf;
bytes32 internal constant _ALLOW_SHARE_PRICE_DECREASE_SLOT = 0x22f7033891e85fc76735ebd320e0d3f546da431c4729c2f6d2613b11923aaaed;
bytes32 internal constant _WITHDRAW_BEFORE_REINVESTING_SLOT = 0x4215fbb95dc0890d3e1660fb9089350f2d3f350c0a756934874cae6febf42a79;
bytes32 internal constant _PAUSED_SLOT = 0xf1cf856d03630b74791fc293cfafd739932a5a075b02d357fb7a726a38777930;
bytes32 internal constant _DECIMALS_SLOT = 0x246bc3666321037fcc8ce5afddcaab1759373f2b839e69dcb1f4c90cffa41f37;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
constructor() {
assert(_STRATEGY_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.strategy")) - 1));
assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.underlying")) - 1));
assert(_UNDERLYING_UNIT_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.underlyingUnit")) - 1));
assert(_VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.vaultFractionToInvestNumerator")) - 1));
assert(_VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.vaultFractionToInvestDenominator")) - 1));
assert(_NEXT_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.nextImplementation")) - 1));
assert(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.nextImplementationTimestamp")) - 1));
assert(_NEXT_STRATEGY_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.nextStrategy")) - 1));
assert(_NEXT_STRATEGY_TIMESTAMP_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.nextStrategyTimestamp")) - 1));
assert(_ALLOW_SHARE_PRICE_DECREASE_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.allowSharePriceDecrease")) - 1));
assert(_WITHDRAW_BEFORE_REINVESTING_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.withdrawBeforeReinvesting")) - 1));
assert(_PAUSED_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.paused")) - 1));
assert(_DECIMALS_SLOT == bytes32(uint256(keccak256("eip1967.vaultStorage.decimals")) - 1));
}
function initialize(
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator,
uint256 _underlyingUnit
) public initializer {
_setUnderlying(_underlying);
_setVaultFractionToInvestNumerator(_toInvestNumerator);
_setVaultFractionToInvestDenominator(_toInvestDenominator);
_setUnderlyingUnit(_underlyingUnit);
_setNextStrategyTimestamp(0);
_setNextStrategy(address(0));
_setAllowSharePriceDecrease(false);
_setWithdrawBeforeReinvesting(false);
}
function _setDecimals(uint256 _value) internal {
setUint256(_DECIMALS_SLOT, _value);
}
function _decimals() internal view returns (uint256) {
return getUint256(_DECIMALS_SLOT);
}
function _setStrategy(address _address) internal {
setAddress(_STRATEGY_SLOT, _address);
}
function _strategy() internal view returns (address) {
return getAddress(_STRATEGY_SLOT);
}
function _setUnderlying(address _address) internal {
setAddress(_UNDERLYING_SLOT, _address);
}
function _underlying() internal view returns (address) {
return getAddress(_UNDERLYING_SLOT);
}
function _setUnderlyingUnit(uint256 _value) internal {
setUint256(_UNDERLYING_UNIT_SLOT, _value);
}
function _underlyingUnit() internal view returns (uint256) {
return getUint256(_UNDERLYING_UNIT_SLOT);
}
function _setVaultFractionToInvestNumerator(uint256 _value) internal {
setUint256(_VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT, _value);
}
function _vaultFractionToInvestNumerator() internal view returns (uint256) {
return getUint256(_VAULT_FRACTION_TO_INVEST_NUMERATOR_SLOT);
}
function _setVaultFractionToInvestDenominator(uint256 _value) internal {
setUint256(_VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT, _value);
}
function _vaultFractionToInvestDenominator() internal view returns (uint256) {
return getUint256(_VAULT_FRACTION_TO_INVEST_DENOMINATOR_SLOT);
}
function _setAllowSharePriceDecrease(bool _value) internal {
setBoolean(_ALLOW_SHARE_PRICE_DECREASE_SLOT, _value);
}
function _allowSharePriceDecrease() internal view returns (bool) {
return getBoolean(_ALLOW_SHARE_PRICE_DECREASE_SLOT);
}
function _setWithdrawBeforeReinvesting(bool _value) internal {
setBoolean(_WITHDRAW_BEFORE_REINVESTING_SLOT, _value);
}
function _withdrawBeforeReinvesting() internal view returns (bool) {
return getBoolean(_WITHDRAW_BEFORE_REINVESTING_SLOT);
}
function _setNextImplementation(address _address) internal {
setAddress(_NEXT_IMPLEMENTATION_SLOT, _address);
}
function _nextImplementation() internal view returns (address) {
return getAddress(_NEXT_IMPLEMENTATION_SLOT);
}
function _setNextImplementationTimestamp(uint256 _value) internal {
setUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT, _value);
}
function _nextImplementationTimestamp() internal view returns (uint256) {
return getUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT);
}
function _setNextStrategy(address _value) internal {
setAddress(_NEXT_STRATEGY_SLOT, _value);
}
function _nextStrategy() internal view returns (address) {
return getAddress(_NEXT_STRATEGY_SLOT);
}
function _setNextStrategyTimestamp(uint256 _value) internal {
setUint256(_NEXT_STRATEGY_TIMESTAMP_SLOT, _value);
}
function _nextStrategyTimestamp() internal view returns (uint256) {
return getUint256(_NEXT_STRATEGY_TIMESTAMP_SLOT);
}
function _implementation() internal view returns (address) {
return getAddress(_IMPLEMENTATION_SLOT);
}
function _paused() internal view returns (bool) {
return getBoolean(_PAUSED_SLOT);
}
function _setPaused(bool _value) internal {
setBoolean(_PAUSED_SLOT, _value);
}
function setBoolean(bytes32 slot, bool _value) internal {
setUint256(slot, _value ? 1 : 0);
}
function getBoolean(bytes32 slot) internal view returns (bool) {
return (getUint256(slot) == 1);
}
function setAddress(bytes32 slot, address _address) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _address)
}
}
function setUint256(bytes32 slot, uint256 _value) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
function getAddress(bytes32 slot) internal view returns (address str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
function getUint256(bytes32 slot) internal view returns (uint256 str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
uint256[50] private ______gap;
}
contracts/base/VaultV1.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./interface/IStrategy.sol";
import "./interface/IVault.sol";
import "./interface/IController.sol";
import "./interface/IUpgradeSource.sol";
import "./inheritance/ControllableInit.sol";
import "./VaultStorage.sol";
import "./interface/IERC4626.sol";
contract VaultV1 is ERC20Upgradeable, IUpgradeSource, ControllableInit, VaultStorage {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Invest(uint256 amount);
event StrategyAnnounced(address newStrategy, uint256 time);
event StrategyChanged(address newStrategy, address oldStrategy);
constructor() {
}
// the function is name differently to not cause inheritance clash in truffle and allows tests
function initializeVault(
address _storage,
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator
) public initializer {
require(_toInvestNumerator <= _toInvestDenominator, "cannot invest more than 100%");
require(_toInvestDenominator != 0, "cannot divide by 0");
__ERC20_init(
string(abi.encodePacked("FARM_", ERC20Upgradeable(_underlying).symbol())),
string(abi.encodePacked("f", ERC20Upgradeable(_underlying).symbol()))
);
_setDecimals(ERC20Upgradeable(_underlying).decimals());
ControllableInit.initialize(
_storage
);
uint256 underlyingUnit = 10 ** uint256(ERC20Upgradeable(address(_underlying)).decimals());
VaultStorage.initialize(
_underlying,
_toInvestNumerator,
_toInvestDenominator,
underlyingUnit
);
}
function strategy() public view returns(address) {
return _strategy();
}
function underlying() public view returns(address) {
return _underlying();
}
function underlyingUnit() public view returns(uint256) {
return _underlyingUnit();
}
function decimals() public view override returns(uint8) {
return uint8(_decimals());
}
function vaultFractionToInvestNumerator() public view returns(uint256) {
return _vaultFractionToInvestNumerator();
}
function vaultFractionToInvestDenominator() public view returns(uint256) {
return _vaultFractionToInvestDenominator();
}
function nextImplementation() public view returns(address) {
return _nextImplementation();
}
function nextImplementationTimestamp() public view returns(uint256) {
return _nextImplementationTimestamp();
}
function nextImplementationDelay() public view returns (uint256) {
return IController(controller()).nextImplementationDelay();
}
modifier whenStrategyDefined() {
require(address(strategy()) != address(0), "Strategy must be defined");
_;
}
// Only smart contracts will be affected by this modifier
modifier defense() {
require(
(msg.sender == tx.origin) || // If it is a normal user and not smart contract,
// then the requirement will pass
!IController(controller()).greyList(msg.sender), // If it is a smart contract, then
"This smart contract has been grey listed" // make sure that it is not on our greyList.
);
_;
}
/**
* Chooses the best strategy and re-invests. If the strategy did not change, it just calls
* doHardWork on the current strategy. Call this through controller to claim hard rewards.
*/
function doHardWork() whenStrategyDefined onlyControllerOrGovernance external {
// ensure that new funds are invested too
invest();
IStrategy(strategy()).doHardWork();
}
/*
* Returns the cash balance across all users in this contract.
*/
function underlyingBalanceInVault() view public returns (uint256) {
return IERC20Upgradeable(underlying()).balanceOf(address(this));
}
/* Returns the current underlying (e.g., DAI's) balance together with
* the invested amount (if DAI is invested elsewhere by the strategy).
*/
function underlyingBalanceWithInvestment() view public returns (uint256) {
if (address(strategy()) == address(0)) {
// initial state, when not set
return underlyingBalanceInVault();
}
return underlyingBalanceInVault().add(IStrategy(strategy()).investedUnderlyingBalance());
}
function getPricePerFullShare() public view returns (uint256) {
return totalSupply() == 0
? underlyingUnit()
: underlyingUnit().mul(underlyingBalanceWithInvestment()).div(totalSupply());
}
/* get the user's share (in underlying)
*/
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256) {
if (totalSupply() == 0) {
return 0;
}
return underlyingBalanceWithInvestment()
.mul(balanceOf(holder))
.div(totalSupply());
}
function nextStrategy() public view returns (address) {
return _nextStrategy();
}
function nextStrategyTimestamp() public view returns (uint256) {
return _nextStrategyTimestamp();
}
function canUpdateStrategy(address _strategy) public view returns (bool) {
bool isStrategyNotSetYet = strategy() == address(0);
bool hasTimelockPassed = block.timestamp > nextStrategyTimestamp() && nextStrategyTimestamp() != 0;
return isStrategyNotSetYet || (_strategy == nextStrategy() && hasTimelockPassed);
}
/**
* Indicates that the strategy update will happen in the future
*/
function announceStrategyUpdate(address _strategy) public onlyControllerOrGovernance {
// records a new timestamp
uint256 when = block.timestamp.add(nextImplementationDelay());
_setNextStrategyTimestamp(when);
_setNextStrategy(_strategy);
emit StrategyAnnounced(_strategy, when);
}
/**
* Finalizes (or cancels) the strategy update by resetting the data
*/
function finalizeStrategyUpdate() public onlyControllerOrGovernance {
_setNextStrategyTimestamp(0);
_setNextStrategy(address(0));
}
function setStrategy(address _strategy) public onlyControllerOrGovernance {
require(canUpdateStrategy(_strategy),
"The strategy exists and switch timelock did not elapse yet");
require(_strategy != address(0), "new _strategy cannot be empty");
require(IStrategy(_strategy).underlying() == address(underlying()), "Vault underlying must match Strategy underlying");
require(IStrategy(_strategy).vault() == address(this), "the strategy does not belong to this vault");
emit StrategyChanged(_strategy, strategy());
if (address(_strategy) != address(strategy())) {
if (address(strategy()) != address(0)) { // if the original strategy (no underscore) is defined
IERC20Upgradeable(underlying()).safeApprove(address(strategy()), 0);
IStrategy(strategy()).withdrawAllToVault();
}
_setStrategy(_strategy);
IERC20Upgradeable(underlying()).safeApprove(address(strategy()), 0);
IERC20Upgradeable(underlying()).safeApprove(address(strategy()), uint256(type(uint).max));
}
finalizeStrategyUpdate();
}
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external onlyGovernance {
require(denominator > 0, "denominator must be greater than 0");
require(numerator <= denominator, "denominator must be greater than or equal to the numerator");
_setVaultFractionToInvestNumerator(numerator);
_setVaultFractionToInvestDenominator(denominator);
}
function rebalance() external onlyControllerOrGovernance {
withdrawAll();
invest();
}
function availableToInvestOut() public view returns (uint256) {
uint256 wantInvestInTotal = underlyingBalanceWithInvestment()
.mul(vaultFractionToInvestNumerator())
.div(vaultFractionToInvestDenominator());
uint256 alreadyInvested = IStrategy(strategy()).investedUnderlyingBalance();
if (alreadyInvested >= wantInvestInTotal) {
return 0;
} else {
uint256 remainingToInvest = wantInvestInTotal.sub(alreadyInvested);
return remainingToInvest <= underlyingBalanceInVault()
// TODO: we think that the "else" branch of the ternary operation is not
// going to get hit
? remainingToInvest : underlyingBalanceInVault();
}
}
function invest() internal whenStrategyDefined {
uint256 availableAmount = availableToInvestOut();
if (availableAmount > 0) {
IERC20Upgradeable(underlying()).safeTransfer(address(strategy()), availableAmount);
emit Invest(availableAmount);
}
}
/*
* Allows for depositing the underlying asset in exchange for shares.
* Approval is assumed.
*/
function deposit(uint256 amount) external nonReentrant defense returns (uint256 minted) {
minted = _deposit(amount, msg.sender, msg.sender);
}
/*
* Allows for depositing the underlying asset in exchange for shares
* assigned to the holder.
* This facilitates depositing for someone else (using DepositHelper)
*/
function depositFor(uint256 amount, address holder) public nonReentrant defense returns (uint256 minted) {
minted = _deposit(amount, msg.sender, holder);
}
function withdraw(uint256 shares) external nonReentrant defense returns (uint256 amtUnderlying) {
amtUnderlying = _withdraw(shares, msg.sender, msg.sender);
}
function withdrawAll() public onlyControllerOrGovernance whenStrategyDefined {
IStrategy(strategy()).withdrawAllToVault();
}
function _deposit(uint256 amount, address sender, address beneficiary) internal virtual returns (uint256) {
require(amount > 0, "Cannot deposit 0");
require(beneficiary != address(0), "holder must be defined");
if (address(strategy()) != address(0)) {
require(IStrategy(strategy()).depositArbCheck(), "Too much arb");
}
uint256 toMint = totalSupply() == 0
? amount
: amount.mul(totalSupply()).div(underlyingBalanceWithInvestment());
_mint(beneficiary, toMint);
IERC20Upgradeable(underlying()).safeTransferFrom(sender, address(this), amount);
// update the contribution amount for the beneficiary
emit IERC4626.Deposit(sender, beneficiary, amount, toMint);
return toMint;
}
function _withdraw(uint256 numberOfShares, address receiver, address owner) internal virtual returns (uint256) {
require(totalSupply() > 0, "Vault has no shares");
require(numberOfShares > 0, "numberOfShares must be greater than 0");
uint256 totalSupply = totalSupply();
address sender = msg.sender;
if (sender != owner) {
uint256 currentAllowance = allowance(owner, sender);
if (currentAllowance != uint(type(uint).max)) {
require(currentAllowance >= numberOfShares, "ERC20: transfer amount exceeds allowance");
_approve(owner, sender, currentAllowance - numberOfShares);
}
}
_burn(owner, numberOfShares);
uint256 underlyingAmountToWithdraw = underlyingBalanceWithInvestment()
.mul(numberOfShares)
.div(totalSupply);
if (underlyingAmountToWithdraw > underlyingBalanceInVault()) {
// withdraw everything from the strategy to accurately check the share value
if (numberOfShares == totalSupply) {
IStrategy(strategy()).withdrawAllToVault();
} else {
uint256 missing = underlyingAmountToWithdraw.sub(underlyingBalanceInVault());
IStrategy(strategy()).withdrawToVault(missing);
}
// recalculate to improve accuracy
underlyingAmountToWithdraw = MathUpgradeable.min(underlyingBalanceWithInvestment()
.mul(numberOfShares)
.div(totalSupply), underlyingBalanceInVault());
}
IERC20Upgradeable(underlying()).safeTransfer(receiver, underlyingAmountToWithdraw);
// update the withdrawal amount for the holder
emit IERC4626.Withdraw(sender, receiver, owner, underlyingAmountToWithdraw, numberOfShares);
return underlyingAmountToWithdraw;
}
/**
* Schedules an upgrade for this vault's proxy.
*/
function scheduleUpgrade(address impl) public onlyGovernance {
_setNextImplementation(impl);
_setNextImplementationTimestamp(block.timestamp.add(nextImplementationDelay()));
}
function shouldUpgrade() external view override returns (bool, address) {
return (
nextImplementationTimestamp() != 0
&& block.timestamp > nextImplementationTimestamp()
&& nextImplementation() != address(0),
nextImplementation()
);
}
function finalizeUpgrade() external override onlyGovernance {
_setNextImplementation(address(0));
_setNextImplementationTimestamp(0);
}
}contracts/base/VaultV2.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "./interface/IERC4626.sol";
import "./VaultV1.sol";
contract VaultV2 is IERC4626, VaultV1 {
/// By default, the constant `10` is a uint8. This implicitly converts it to `uint256`
uint256 public constant TEN = 10;
function asset() public view override returns (address) {
return underlying();
}
function totalAssets() public view virtual override returns (uint256) {
return underlyingBalanceWithInvestment();
}
function assetsPerShare() public view override returns (uint256) {
return convertToAssets(TEN ** decimals());
}
function assetsOf(address _depositor) public view override returns (uint256) {
return totalAssets() * balanceOf(_depositor) / totalSupply();
}
function maxDeposit(address /*caller*/) public view virtual override returns (uint256) {
return uint(type(uint).max);
}
function previewDeposit(uint256 _assets) public view override returns (uint256) {
return convertToShares(_assets);
}
function deposit(uint256 _assets, address _receiver) public override nonReentrant defense returns (uint256) {
uint256 shares = _deposit(_assets, msg.sender, _receiver);
return shares;
}
function maxMint(address /*caller*/) public view virtual override returns (uint256) {
return uint(type(uint).max);
}
function previewMint(uint256 _shares) public view override returns (uint256) {
return convertToAssets(_shares);
}
function mint(uint256 _shares, address _receiver) public override nonReentrant defense returns (uint256) {
uint assets = convertToAssets(_shares);
_deposit(assets, msg.sender, _receiver);
return assets;
}
function maxWithdraw(address _caller) public view override returns (uint256) {
return assetsOf(_caller);
}
function previewWithdraw(uint256 _assets) public view override returns (uint256) {
return convertToShares(_assets);
}
function withdraw(
uint256 _assets,
address _receiver,
address _owner
)
public override
nonReentrant
defense
returns (uint256) {
uint256 shares = convertToShares(_assets);
_withdraw(shares, _receiver, _owner);
return shares;
}
function maxRedeem(address _caller) public view override returns (uint256) {
return balanceOf(_caller);
}
function previewRedeem(uint256 _shares) public view override returns (uint256) {
return convertToAssets(_shares);
}
function redeem(
uint256 _shares,
address _receiver,
address _owner
)
public override
nonReentrant
defense
returns (uint256) {
uint256 assets = _withdraw(_shares, _receiver, _owner);
return assets;
}
// ========================= Conversion Functions =========================
function convertToAssets(uint256 _shares) public view returns (uint256) {
return totalAssets() == 0 || totalSupply() == 0
? _shares * (TEN ** ERC20Upgradeable(underlying()).decimals()) / (TEN ** decimals())
: _shares * totalAssets() / totalSupply();
}
function convertToShares(uint256 _assets) public view returns (uint256) {
return totalAssets() == 0 || totalSupply() == 0
? _assets * (TEN ** decimals()) / (TEN ** ERC20Upgradeable(underlying()).decimals())
: _assets * totalSupply() / totalAssets();
}
}
contracts/base/inheritance/ControllableInit.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "./GovernableInit.sol";
// A clone of Governable supporting the Initializable interface and pattern
contract ControllableInit is GovernableInit {
constructor() {
}
function initialize(address _storage) public override initializer {
GovernableInit.initialize(_storage);
}
modifier onlyController() {
require(Storage(_storage()).isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((Storage(_storage()).isController(msg.sender) || Storage(_storage()).isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return Storage(_storage()).controller();
}
}
contracts/base/inheritance/GovernableInit.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "../upgradability/ReentrancyGuardUpgradeable.sol";
import "./Storage.sol";
// A clone of Governable supporting the Initializable interface and pattern
contract GovernableInit is ReentrancyGuardUpgradeable {
bytes32 internal constant _STORAGE_SLOT = 0xa7ec62784904ff31cbcc32d09932a58e7f1e4476e1d041995b37c917990b16dc;
modifier onlyGovernance() {
require(Storage(_storage()).isGovernance(msg.sender), "Not governance");
_;
}
constructor() {
assert(_STORAGE_SLOT == bytes32(uint256(keccak256("eip1967.governableInit.storage")) - 1));
}
function initialize(address _store) public virtual initializer {
_setStorage(_store);
ReentrancyGuardUpgradeable.initialize();
}
function _setStorage(address newStorage) private {
bytes32 slot = _STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newStorage)
}
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
_setStorage(_store);
}
function _storage() internal view returns (address str) {
bytes32 slot = _STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
function governance() public view returns (address) {
return Storage(_storage()).governance();
}
}
contracts/base/inheritance/Storage.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
contract Storage {
address public governance;
address public controller;
constructor() {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
contracts/base/interface/IController.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
interface IController {
// ========================= Events =========================
event QueueProfitSharingChange(uint profitSharingNumerator, uint validAtTimestamp);
event ConfirmProfitSharingChange(uint profitSharingNumerator);
event QueueStrategistFeeChange(uint strategistFeeNumerator, uint validAtTimestamp);
event ConfirmStrategistFeeChange(uint strategistFeeNumerator);
event QueuePlatformFeeChange(uint platformFeeNumerator, uint validAtTimestamp);
event ConfirmPlatformFeeChange(uint platformFeeNumerator);
event QueueNextImplementationDelay(uint implementationDelay, uint validAtTimestamp);
event ConfirmNextImplementationDelay(uint implementationDelay);
event AddedStakingContract(address indexed stakingContract);
event RemovedStakingContract(address indexed stakingContract);
event SharePriceChangeLog(
address indexed vault,
address indexed strategy,
uint256 oldSharePrice,
uint256 newSharePrice,
uint256 timestamp
);
// ==================== Functions ====================
/**
* An EOA can safely interact with the system no matter what. If you're using Metamask, you're using an EOA. Only
* smart contracts may be affected by this grey list. This contract will not be able to ban any EOA from the system
* even if an EOA is being added to the greyList, he/she will still be able to interact with the whole system as if
* nothing happened. Only smart contracts will be affected by being added to the greyList. This grey list is only
* used in VaultV3.sol, see the code there for reference
*/
function greyList(address _target) external view returns (bool);
function addressWhiteList(address _target) external view returns (bool);
function codeWhiteList(address _target) external view returns (bool);
function addToWhitelist(address _target) external;
function addCodeToWhitelist(address _target) external;
function store() external view returns (address);
function governance() external view returns (address);
function doHardWork(address _vault) external;
function addHardWorker(address _worker) external;
function removeHardWorker(address _worker) external;
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
/**
* @return The targeted profit token to convert all-non-compounding rewards to. Defaults to WETH.
*/
function targetToken() external view returns (address);
function setTargetToken(address _targetToken) external;
function profitSharingReceiver() external view returns (address);
function setProfitSharingReceiver(address _profitSharingReceiver) external;
function protocolFeeReceiver() external view returns (address);
function setProtocolFeeReceiver(address _protocolFeeReceiver) external;
function rewardForwarder() external view returns (address);
function setRewardForwarder(address _rewardForwarder) external;
function universalLiquidator() external view returns (address);
function setUniversalLiquidator(address _universalLiquidator) external;
function dolomiteYieldFarmingRouter() external view returns (address);
function setDolomiteYieldFarmingRouter(address _value) external;
function nextImplementationDelay() external view returns (uint256);
function profitSharingNumerator() external view returns (uint256);
function strategistFeeNumerator() external view returns (uint256);
function platformFeeNumerator() external view returns (uint256);
function feeDenominator() external view returns (uint256);
function setProfitSharingNumerator(uint _profitSharingNumerator) external;
function confirmSetProfitSharingNumerator() external;
function setStrategistFeeNumerator(uint _strategistFeeNumerator) external;
function confirmSetStrategistFeeNumerator() external;
function setPlatformFeeNumerator(uint _platformFeeNumerator) external;
function confirmSetPlatformFeeNumerator() external;
function setNextImplementationDelay(uint256 _nextImplementationDelay) external;
function confirmNextImplementationDelay() external;
function nextProfitSharingNumerator() external view returns (uint256);
function nextProfitSharingNumeratorTimestamp() external view returns (uint256);
function nextStrategistFeeNumerator() external view returns (uint256);
function nextStrategistFeeNumeratorTimestamp() external view returns (uint256);
function nextPlatformFeeNumerator() external view returns (uint256);
function nextPlatformFeeNumeratorTimestamp() external view returns (uint256);
function tempNextImplementationDelay() external view returns (uint256);
function tempNextImplementationDelayTimestamp() external view returns (uint256);
function hardWorkers(address _worker) external view returns (bool);
}
contracts/base/interface/IERC4626.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IERC4626 {
// ========================= Events =========================
/**
* Caller has exchanged assets for shares, and transferred those shares to owner.
*
* MUST be emitted when tokens are deposited into the Vault via the mint and deposit methods.
*/
event Deposit(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/**
* Caller has exchanged shares, owned by owner, for assets, and transferred those assets to receiver.
*
* MUST be emitted when shares are withdrawn from the Vault in ERC4626.redeem or ERC4626.withdraw methods.
*/
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
// ========================= Functions =========================
/**
* @return assetTokenAddress The address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @return totalManagedAssets Total amount of the underlying asset that is “managed” by Vault. SHOULD include any compounding that
* occurs from yield. MUST be inclusive of any fees that are charged against assets in the Vault.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @return assetsPerUnitShare The amount of underlying the Vault would exchange for 1 unit of shares, in an ideal scenario where all
* the conditions are met. MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* MUST NOT show any variations depending on the caller. MUST NOT reflect slippage or other on-chain
* conditions, when performing the actual exchange. MUST NOT revert unless due to integer overflow caused
* by an unreasonably large input. MUST round down towards 0. This calculation MAY NOT reflect the
* “per-user” price-per-share, and instead should reflect the “average-user’s” price-per-share, meaning
* what the average user should expect to see when exchanging to and from. This function should normally
* return more than `10 ** underlying().decimals`.
*/
function assetsPerShare() external view returns (uint256 assetsPerUnitShare);
/**
* @return assets Total amount of the underlying asset that is “managed” by Vault for the `depositor`. SHOULD include any
* compounding that occurs from yield. MUST be inclusive of any fees that are charged against assets in the
* Vault.
*/
function assetsOf(address depositor) external view returns (uint256 assets);
/**
* Maximum amount of the underlying asset that can be deposited into the Vault for the receiver, through a deposit
* call. MUST return the maximum amount of assets deposit would allow to be deposited for receiver and not cause a
* revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if
* necessary). This assumes that the user has infinite assets, i.e. MUST NOT rely on balanceOf of asset. MUST factor
* in both global and user-specific limits, like if deposits are entirely disabled (even temporarily) it MUST return
* 0. MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
*/
function maxDeposit(address caller) external view returns (uint256 maxAssets);
/**
* Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current
* on-chain conditions.
*
* MUST return as close to and no more than the exact amount of Vault shares that would be
* minted in a deposit call in the same transaction. I.e. deposit should return the same or more shares as
* previewDeposit if called in the same transaction. MUST NOT account for deposit limits like those returned from
* maxDeposit and should always act as though the deposit would be accepted, regardless if the user has enough
* tokens approved, etc.
*
* MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
*
* MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also
* cause deposit to revert.
*
* Note that any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* MUST emit the Deposit event.
*
* MUST support ERC-20 approve / transferFrom on asset as a deposit flow. MAY support an additional flow in which
* the underlying tokens are owned by the Vault contract before the deposit execution, and are accounted for during
* deposit.
*
* MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* Note that most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* Maximum amount of shares that can be minted from the Vault for the receiver, through a mint call.
*
* MUST return the maximum amount of shares mint would allow to be deposited to receiver and not cause a revert,
* which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary).
* This assumes that the user has infinite assets, i.e. MUST NOT rely on balanceOf of asset.
*
* MUST factor in both global and user-specific limits, like if mints are entirely disabled (even temporarily) it
* MUST return 0.
*
* MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
*/
function maxMint(address caller) external view returns (uint256 maxShares);
/**
* Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current
* on-chain conditions.
*
* MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call in
* the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the same
* transaction.
*
* MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint would
* be accepted, regardless if the user has enough tokens approved, etc.
*
* MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
*
* MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also
* cause mint to revert.
*
* Note that any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* MUST emit the Deposit event.
*
* MUST support ERC-20 approve / transferFrom on asset as a mint flow. MAY support an additional flow in which the
* underlying tokens are owned by the Vault contract before the mint execution, and are accounted for during mint.
*
* MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* Note that most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* Maximum amount of the underlying asset that can be withdrawn from the owner balance in the Vault, through a
* withdraw call.
*
* MUST return the maximum amount of assets that could be transferred from owner through withdraw and not cause a
* revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if
* necessary).
*
* MUST factor in both global and user-specific limits, like if withdrawals are entirely disabled (even temporarily)
* it MUST return 0.
*/
function maxWithdraw(address caller) external view returns (uint256 maxAssets);
/**
* Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given
* current on-chain conditions.
*
* MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if called
* in the same transaction.
*
* MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though the
* withdrawal would be accepted, regardless if the user has enough shares, etc.
*
* MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
*
* MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also
* cause withdraw to revert.
*
* Note that any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage
* in share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* MUST emit the Withdraw event.
*
* MUST support a withdraw flow where the shares are burned from owner directly where owner is msg.sender or
* msg.sender has ERC-20 approval over the shares of owner. MAY support an additional flow in which the shares are
* transferred to the Vault contract before the withdraw execution, and are accounted for during withdraw.
*
* MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner not
* having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* Maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, through a redeem call.
*
* MUST return the maximum amount of shares that could be transferred from owner through redeem and not cause a
* revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if
* necessary).
*
* MUST factor in both global and user-specific limits, like if redemption is entirely disabled (even temporarily)
* it MUST return 0.
*/
function maxRedeem(address caller) external view returns (uint256 maxShares);
/**
* Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, given
* current on-chain conditions.
*
* MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call in
* the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the same
* transaction.
*
* MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
*
* MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
*
* MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also
* cause redeem to revert.
*
* Note that any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* MUST emit the Withdraw event.
*
* MUST support a redeem flow where the shares are burned from owner directly where owner is msg.sender or
* msg.sender has ERC-20 approval over the shares of owner. MAY support an additional flow in which the shares are
* transferred to the Vault contract before the redeem execution, and are accounted for during redeem.
*
* MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner not
* having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
function convertToAssets(uint256 shares) external view returns (uint256 assets);
function convertToShares(uint256 assets) external view returns (uint256 shares);
}
contracts/base/interface/IInKindStrategy.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
/**
* @dev Minimal interface for the in-kind functions the strategy must expose.
* Only called while in-kind redemptions are explicitly enabled by governance,
* so strategies without these functions remain compatible with these vaults.
*/
interface IInKindStrategy {
function withdrawInKind(uint256 shareNumerator, uint256 shareDenominator, address receiver) external returns (uint256);
function previewWithdrawInKind(uint256 shareNumerator, uint256 shareDenominator) external view returns (uint256);
function syncBalance() external;
function syncedInvestedUnderlyingBalance() external view returns (uint256);
function rewardPool() external view returns (address);
}
contracts/base/interface/IStrategy.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
interface IStrategy {
/// @notice declared as public so child contract can call it
function isUnsalvageableToken(address token) external view returns (bool);
function salvageToken(address recipient, address token, uint amount) external;
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 _amount) external;
function investedUnderlyingBalance() external view returns (uint256);
function doHardWork() external;
function depositArbCheck() external view returns (bool);
function strategist() external view returns (address);
/**
* @return The value of any accumulated rewards that are under control by the strategy. Each index corresponds with
* the tokens in `rewardTokens`. This function is not a `view`, because some protocols, like Curve, need
* writeable functions to get the # of claimable reward tokens
*/
function getRewardPoolValues() external returns (uint256[] memory);
function morphoClaim(address _distr, bytes calldata _txData) external;
}
contracts/base/interface/IUpgradeSource.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
interface IUpgradeSource {
function shouldUpgrade() external view returns (bool, address);
function finalizeUpgrade() external;
}
contracts/base/interface/IVault.sol
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
interface IVault {
function initializeVault(
address _storage,
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator
) external;
function balanceOf(address _holder) external view returns (uint256);
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function underlyingUnit() external view returns (uint);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function announceStrategyUpdate(address _strategy) external;
function setVaultFractionToInvest(uint256 _numerator, uint256 _denominator) external;
function deposit(uint256 _amount) external;
function deposit(uint256 _amount, address _receiver) external;
function depositFor(uint256 _amount, address _holder) external;
function withdrawAll() external;
function withdraw(uint256 _numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address _holder) view external returns (uint256);
/**
* The total amount available to be deposited from this vault into the strategy, while adhering to the
* `vaultFractionToInvestNumerator` and `vaultFractionToInvestDenominator` rules
*/
function availableToInvestOut() external view returns (uint256);
/**
* This should be callable only by the controller (by the hard worker) or by governance
*/
function doHardWork() external;
function decimals() external view returns (uint8);
}
contracts/base/upgradability/ReentrancyGuardUpgradeable.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.26;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* Same old `ReentrancyGuard`, but can be used by upgradable contracts
*/
contract ReentrancyGuardUpgradeable is Initializable {
bytes32 internal constant _NOT_ENTERED_SLOT = 0x62ae7bf2df4e95c187ea09c8c47c3fc3d9abc36298f5b5b6c5e2e7b4b291fe25;
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_getNotEntered(_NOT_ENTERED_SLOT), "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_setNotEntered(_NOT_ENTERED_SLOT, false);
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_setNotEntered(_NOT_ENTERED_SLOT, true);
}
constructor() {
assert(_NOT_ENTERED_SLOT == bytes32(uint256(keccak256("eip1967.reentrancyGuard.notEntered")) - 1));
}
function initialize() public initializer {
_setNotEntered(_NOT_ENTERED_SLOT, true);
}
function _getNotEntered(bytes32 slot) private view returns (bool) {
uint str;
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
return str == 1;
}
function _setNotEntered(bytes32 slot, bool _value) private {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.