UNPKG

@b0dhidharma/yswaps

Version:
20 lines 167 kB
{ "language": "Solidity", "sources": { "contracts/mock/ERC20Mock.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\nimport '@openzeppelin/contracts/token/ERC20/ERC20.sol';\n\ncontract ERC20Mock is ERC20 {\n constructor(\n string memory name,\n string memory symbol,\n address initialAccount,\n uint256 initialBalance\n ) ERC20(name, symbol) {\n _mint(initialAccount, initialBalance);\n }\n\n function mint(address account, uint256 amount) public {\n _mint(account, amount);\n }\n\n function burn(address account, uint256 amount) public {\n _burn(account, amount);\n }\n\n function transferInternal(\n address from,\n address to,\n uint256 value\n ) public {\n _transfer(from, to, value);\n }\n\n function approveInternal(\n address owner,\n address spender,\n uint256 value\n ) public {\n _approve(owner, spender, value);\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/ERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n\n uint256 currentAllowance = _allowances[sender][_msgSender()];\n require(currentAllowance >= amount, \"ERC20: transfer amount exceeds allowance\");\n unchecked {\n _approve(sender, _msgSender(), currentAllowance - amount);\n }\n\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n uint256 currentAllowance = _allowances[_msgSender()][spender];\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(_msgSender(), spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `sender` to `recipient`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(\n address sender,\n address recipient,\n uint256 amount\n ) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n uint256 senderBalance = _balances[sender];\n require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[sender] = senderBalance - amount;\n }\n _balances[recipient] += amount;\n\n emit Transfer(sender, recipient, amount);\n\n _afterTokenTransfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" }, "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" }, "@openzeppelin/contracts/utils/Context.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" }, "contracts/utils/BaseStrategy.sol": { "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.8.0 <0.9.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\nimport '@openzeppelin/contracts/token/ERC20/ERC20.sol';\nimport '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\n\nstruct StrategyParams {\n uint256 performanceFee;\n uint256 activation;\n uint256 debtRatio;\n uint256 minDebtPerHarvest;\n uint256 maxDebtPerHarvest;\n uint256 lastReport;\n uint256 totalDebt;\n uint256 totalGain;\n uint256 totalLoss;\n bool enforceChangeLimit;\n uint256 profitLimitRatio;\n uint256 lossLimitRatio;\n address customCheck;\n}\n\ninterface VaultAPI is IERC20 {\n function name() external view returns (string calldata);\n\n function symbol() external view returns (string calldata);\n\n function decimals() external view returns (uint256);\n\n function apiVersion() external pure returns (string memory);\n\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 expiry,\n bytes calldata signature\n ) external returns (bool);\n\n // NOTE: Vyper produces multiple signatures for a given function with \"default\" args\n function deposit() external returns (uint256);\n\n function deposit(uint256 amount) external returns (uint256);\n\n function deposit(uint256 amount, address recipient) external returns (uint256);\n\n // NOTE: Vyper produces multiple signatures for a given function with \"default\" args\n function withdraw() external returns (uint256);\n\n function withdraw(uint256 maxShares) external returns (uint256);\n\n function withdraw(uint256 maxShares, address recipient) external returns (uint256);\n\n function token() external view returns (address);\n\n function strategies(address _strategy) external view returns (StrategyParams memory);\n\n function pricePerShare() external view returns (uint256);\n\n function totalAssets() external view returns (uint256);\n\n function depositLimit() external view returns (uint256);\n\n function maxAvailableShares() external view returns (uint256);\n\n /**\n * View how much the Vault would increase this Strategy's borrow limit,\n * based on its present performance (since its last report). Can be used to\n * determine expectedReturn in your Strategy.\n */\n function creditAvailable() external view returns (uint256);\n\n /**\n * View how much the Vault would like to pull back from the Strategy,\n * based on its present performance (since its last report). Can be used to\n * determine expectedReturn in your Strategy.\n */\n function debtOutstanding() external view returns (uint256);\n\n /**\n * View how much the Vault expect this Strategy to return at the current\n * block, based on its present performance (since its last report). Can be\n * used to determine expectedReturn in your Strategy.\n */\n function expectedReturn() external view returns (uint256);\n\n /**\n * This is the main contact point where the Strategy interacts with the\n * Vault. It is critical that this call is handled as intended by the\n * Strategy. Therefore, this function will be called by BaseStrategy to\n * make sure the integration is correct.\n */\n function report(\n uint256 _gain,\n uint256 _loss,\n uint256 _debtPayment\n ) external returns (uint256);\n\n /**\n * This function should only be used in the scenario where the Strategy is\n * being retired but no migration of the positions are possible, or in the\n * extreme scenario that the Strategy needs to be put into \"Emergency Exit\"\n * mode in order for it to exit as quickly as possible. The latter scenario\n * could be for any reason that is considered \"critical\" that the Strategy\n * exits its position as fast as possible, such as a sudden change in\n * market conditions leading to losses, or an imminent failure in an\n * external dependency.\n */\n function revokeStrategy() external;\n\n /**\n * View the governance address of the Vault to assert privileged functions\n * can only be called by governance. The Strategy serves the Vault, so it\n * is subject to governance defined by the Vault.\n */\n function governance() external view returns (address);\n\n /**\n * View the management address of the Vault to assert privileged functions\n * can only be called by management. The Strategy serves the Vault, so it\n * is subject to management defined by the Vault.\n */\n function management() external view returns (address);\n\n /**\n * View the guardian address of the Vault to assert privileged functions\n * can only be called by guardian. The Strategy serves the Vault, so it\n * is subject to guardian defined by the Vault.\n */\n function guardian() external view returns (address);\n}\n\n/**\n * This interface is here for the keeper bot to use.\n */\ninterface StrategyAPI {\n function name() external view returns (string memory);\n\n function vault() external view returns (address);\n\n function want() external view returns (address);\n\n function apiVersion() external pure returns (string memory);\n\n function keeper() external view returns (address);\n\n function isActive() external view returns (bool);\n\n function delegatedAssets() external view returns (uint256);\n\n function estimatedTotalAssets() external view returns (uint256);\n\n function tendTrigger(uint256 callCost) external view returns (bool);\n\n function tend() external;\n\n function harvestTrigger(uint256 callCost) external view returns (bool);\n\n function harvest() external;\n\n event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);\n}\n\n/**\n * @title Yearn Base Strategy\n * @author yearn.finance\n * @notice\n * BaseStrategy implements all of the required functionality to interoperate\n * closely with the Vault contract. This contract should be inherited and the\n * abstract methods implemented to adapt the Strategy to the particular needs\n * it has to create a return.\n *\n * Of special interest is the relationship between `harvest()` and\n * `vault.report()'. `harvest()` may be called simply because enough time has\n * elapsed since the last report, and not because any funds need to be moved\n * or positions adjusted. This is critical so that the Vault may maintain an\n * accurate picture of the Strategy's performance. See `vault.report()`,\n * `harvest()`, and `harvestTrigger()` for further details.\n */\n\nabstract contract BaseStrategy {\n using SafeERC20 for IERC20;\n string public metadataURI;\n\n /**\n * @notice\n * Used to track which version of `StrategyAPI` this Strategy\n * implements.\n * @dev The Strategy's version must match the Vault's `API_VERSION`.\n * @return A string which holds the current API version of this contract.\n */\n function apiVersion() public pure returns (string memory) {\n return '0.4.2';\n }\n\n /**\n * @notice This Strategy's name.\n * @dev\n * You can use this field to manage the \"version\" of this Strategy, e.g.\n * `StrategySomethingOrOtherV1`. However, \"API Version\" is managed by\n * `apiVersion()` function above.\n * @return This Strategy's name.\n */\n function name() external view virtual returns (string memory);\n\n /**\n * @notice\n * The amount (priced in want) of the total assets managed by this strategy should not count\n * towards Yearn's TVL calculations.\n * @dev\n * You can override this field to set it to a non-zero value if some of the assets of this\n * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.\n * Note that this value must be strictly less than or equal to the amount provided by\n * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.\n * Also note that this value is used to determine the total assets under management by this\n * strategy, for the purposes of computing the management fee in `Vault`\n * @return\n * The amount of assets this strategy manages that should not be included in Yearn's Total Value\n * Locked (TVL) calculation across it's ecosystem.\n */\n function delegatedAssets() external view virtual returns (uint256) {\n return 0;\n }\n\n VaultAPI public vault;\n address public strategist;\n address public rewards;\n address public keeper;\n\n IERC20 public want;\n\n // So indexers can keep track of this\n event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);\n\n event UpdatedStrategist(address newStrategist);\n\n event UpdatedKeeper(address newKeeper);\n\n event UpdatedRewards(address rewards);\n\n event UpdatedMinReportDelay(uint256 delay);\n\n event UpdatedMaxReportDelay(uint256 delay);\n\n event UpdatedProfitFactor(uint256 profitFactor);\n\n event UpdatedDebtThreshold(uint256 debtThreshold);\n\n event EmergencyExitEnabled();\n\n event UpdatedMetadataURI(string metadataURI);\n\n // The minimum number of seconds between harvest calls. See\n // `setMinReportDelay()` for more details.\n uint256 public minReportDelay;\n\n // The maximum number of seconds between harvest calls. See\n // `setMaxReportDelay()` for more details.\n uint256 public maxReportDelay;\n\n // The minimum multiple that `callCost` must be above the credit/profit to\n // be \"justifiable\". See `setProfitFactor()` for more details.\n uint256 public profitFactor;\n\n // Use this to adjust the threshold at which running a debt causes a\n // harvest trigger. See `setDebtThreshold()` for more details.\n uint256 public debtThreshold;\n\n // See note on `setEmergencyExit()`.\n bool public emergencyExit;\n\n // modifiers\n modifier onlyAuthorized() {\n require(msg.sender == strategist || msg.sender == governance(), '!authorized');\n _;\n }\n\n modifier onlyEmergencyAuthorized() {\n require(\n msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),\n '!authorized'\n );\n _;\n }\n\n modifier onlyStrategist() {\n require(msg.sender == strategist, '!strategist');\n _;\n }\n\n modifier onlyGovernance() {\n require(msg.sender == governance(), '!authorized');\n _;\n }\n\n modifier onlyKeepers() {\n require(\n msg.sender == keeper ||\n msg.sender == strategist ||\n msg.sender == governance() ||\n msg.sender == vault.guardian() ||\n msg.sender == vault.management(),\n '!authorized'\n );\n _;\n }\n\n constructor(address _vault) {\n _initialize(_vault, msg.sender, msg.sender, msg.sender);\n }\n\n /**\n * @notice\n * Initializes the Strategy, this is called only once, when the\n * contract is deployed.\n * @dev `_vault` should implement `VaultAPI`.\n * @param _vault The address of the Vault responsible for this Strategy.\n * @param _strategist The address to assign as `strategist`.\n * The strategist is able to change the reward address\n * @param _rewards The address to use for pulling rewards.\n * @param _keeper The adddress of the _keeper. _keeper\n * can harvest and tend a strategy.\n */\n function _initialize(\n address _vault,\n address _strategist,\n address _rewards,\n address _keeper\n ) internal {\n require(address(want) == address(0), 'Strategy already initialized');\n\n vault = VaultAPI(_vault);\n want = IERC20(vault.token());\n want.safeApprove(_vault, type(uint256).max); // Give Vault unlimited access (might save gas)\n strategist = _strategist;\n rewards = _rewards;\n keeper = _keeper;\n // initialize variables\n minReportDelay = 0;\n maxReportDelay = 86400;\n profitFactor = 100;\n debtThreshold = 0;\n\n vault.approve(rewards, type(uint256).max); // Allow rewards to be pulled\n }\n\n /**\n * @notice\n * Used to change `strategist`.\n *\n * This may only be called by governance or the existing strategist.\n * @param _strategist The new address to assign as `strategist`.\n */\n function setStrategist(address _strategist) external onlyAuthorized {\n require(_strategist != address(0));\n strategist = _strategist;\n emit UpdatedStrategist(_strategist);\n }\n\n /**\n * @notice\n * Used to change `keeper`.\n *\n * `keeper` is the only address that may call `tend()` or `harvest()`,\n * other than `governance()` or `strategist`. However, unlike\n * `governance()` or `strategist`, `keeper` may *only* call `tend()`\n * and `harvest()`, and no other authorized functions, following the\n * principle of least privilege.\n *\n * This may only be called by governance or the strategist.\n * @param _keeper The new address to assign as `keeper`.\n */\n function setKeeper(address _keeper) external onlyAuthorized {\n require(_keeper != address(0));\n keeper = _keeper;\n emit UpdatedKeeper(_keeper);\n }\n\n /**\n * @notice\n * Used to change `rewards`. EOA or smart contract which has the permission\n * to pull rewards from the vault.\n *\n * This may only be called by the strategist.\n * @param _rewards The address to use for pulling rewards.\n */\n function setRewards(address _rewards) external onlyStrategist {\n require(_rewards != address(0));\n vault.approve(rewards, 0);\n rewards = _rewards;\n vault.approve(rewards, type(uint256).max);\n emit UpdatedRewards(_rewards);\n }\n\n /**\n * @notice\n * Used to change `minReportDelay`. `minReportDelay` is the minimum number\n * of blocks that should pass for `harvest()` to be called.\n *\n * For external keepers (such as the Keep3r network), this is the minimum\n * time between jobs to wait. (see `harvestTrigger()`\n * for more details.)\n *\n * This may only be called by governance or the strategist.\n * @param _delay The minimum number of seconds to wait between harvests.\n */\n function setMinReportDelay(uint256 _delay) external onlyAuthorized {\n minReportDelay = _delay;\n emit UpdatedMinReportDelay(_delay);\n }\n\n /**\n * @notice\n * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number\n * of blocks that should pass for `harvest()` to be called.\n *\n * For external keepers (such as the Keep3r network), this is the maximum\n * time between jobs to wait. (see `harvestTrigger()`\n * for more details.)\n *\n * This may only be called by governance or the strategist.\n * @param _delay The maximum number of seconds to wait between harvests.\n */\n function setMaxReportDelay(uint256 _delay) external onlyAuthorized {\n maxReportDelay = _delay;\n emit UpdatedMaxReportDelay(_delay);\n }\n\n /**\n * @notice\n * Used to change `profitFactor`. `profitFactor` is used to determine\n * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`\n * for more details.)\n *\n * This may only be called by governance or the strategist.\n * @param _profitFactor A ratio to multiply anticipated\n * `harvest()` gas cost against.\n */\n function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {\n profitFactor = _profitFactor;\n emit UpdatedProfitFactor(_profitFactor);\n }\n\n /**\n * @notice\n * Sets how far the Strategy can go into loss without a harvest and report\n * being required.\n *\n * By default this is 0, meaning any losses would cause a harvest which\n * will subsequently report the loss to the Vault for tracking. (See\n * `harvestTrigger()` for more details.)\n *\n * This may only be called by governance or the strategist.\n * @param _debtThreshold How big of a loss this Strategy may carry without\n * being required to report to the Vault.\n */\n function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {\n debtThreshold = _debtThreshold;\n emit UpdatedDebtThreshold(_debtThreshold);\n }\n\n /**\n * @notice\n * Used to change `metadataURI`. `metadataURI` is used to store the URI\n * of the file describing the strategy.\n *\n * This may only be called by governance or the strategist.\n * @param _metadataURI The URI that describe the strategy.\n */\n function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {\n metadataURI = _metadataURI;\n emit UpdatedMetadataURI(_metadataURI);\n }\n\n /**\n * Resolve governance address from Vault contract, used to make assertions\n * on protected functions in the Strategy.\n */\n function governance() internal view returns (address) {\n return vault.governance();\n }\n\n /**\n * @notice\n * Provide an accurate conversion from `_amtInWei` (denominated in wei)\n * to `want` (using the native decimal characteristics of `want`).\n * @dev\n * Care must be taken when working with decimals to assure that the conversion\n * is compatible. As an example:\n *\n * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),\n * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)\n *\n * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`\n * @return The amount in `want` of `_amtInEth` converted to `want`\n **/\n function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);\n\n /**\n * @notice\n * Provide an accurate estimate for the total amount of assets\n * (principle + return) that this Strategy is currently managing,\n * denominated in terms of `want` tokens.\n *\n * This total should be \"realizable\" e.g. the total value that could\n * *actually* be obtained from this Strategy if it were to divest its\n * entire position based on current on-chain conditions.\n * @dev\n * Care must be taken in using this function, since it relies on external\n * systems, which could be manipulated by the attacker to give an inflated\n * (or reduced) value produced by this function, based on current on-chain\n * conditions (e.g. this function is possible to influence through\n * flashloan attacks, oracle manipulations, or other DeFi attack\n * mechanisms).\n *\n * It is up to governance to use this function to correctly order this\n * Strategy relative to its peers in the withdrawal queue to minimize\n * losses for the Vault based on sudden withdrawals. This value should be\n * higher than the total debt of the Strategy and higher than its expected\n * value to be \"safe\".\n * @return The estimated total assets in this Strategy.\n */\n function estimatedTotalAssets() public view virtual returns (uint256);\n\n /*\n * @notice\n * Provide an indication of whether this strategy is currently \"active\"\n * in that it is managing an active position, or will manage a position in\n * the future. This should correlate to `harvest()` activity, so that Harvest\n * events can be tracked externally by indexing agents.\n * @return True if the strategy is actively managing a position.\n */\n function isActive() public view returns (bool) {\n return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;\n }\n\n /**\n * Perform any Strategy unwinding or other calls necessary to capture the\n * \"free return\" this Strategy has generated since the last time its core\n * position(s) were adjusted. Examples include unwrapping extra rewards.\n * This call is only used during \"normal operation\" of a Strategy, and\n * should be optimized to minimize losses as much as possible.\n *\n * This method returns any realized profits and/or realized losses\n * incurred, and should return the total amounts of profits/losses/debt\n * payments (in `want` tokens) for the Vault's accounting (e.g.\n * `want.balanceOf(this) >= _debtPayment + _profit`).\n *\n * `_debtOutstanding` will be 0 if the Strategy is not past the configured\n * debt limit, otherwise its value will be how far past the debt limit\n * the Strategy is. The Strategy's debt limit is configured in the Vault.\n *\n * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.\n * It is okay for it to be less than `_debtOutstanding`, as that\n * should only used as a guide for how much is left to pay back.\n * Payments should be made to minimize loss from slippage, debt,\n * withdrawal fees, etc.\n *\n * See `vault.debtOutstanding()`.\n */\n function prepareReturn(uint256 _debtOutstanding)\n internal\n virtual\n returns (\n uint256 _profit,\n uint256 _loss,\n uint256 _debtPayment\n );\n\n /**\n * Perform any adjustments to the core position(s) of this Strategy given\n * what change the Vault made in the \"investable capital\" available to the\n * Strategy. Note that all \"free capital\" in the Strategy after the report\n * was made is available for reinvestment. Also note that this number\n * could be 0, and you should handle that scenario accordingly.\n *\n * See comments regarding `_debtOutstanding` on `prepareReturn()`.\n */\n function adjustPosition(uint256 _debtOutstanding) internal virtual;\n\n /**\n * Liquidate up to `_amountNeeded` of `want` of this strategy's positions,\n * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.\n * This function should return the amount of `want` tokens made available by the\n * liquidation. If there is a difference between them, `_loss` indicates whether the\n * difference is due to a realized loss, or if there is some other sitution at play\n * (e.g. locked funds) where the amount made available is less than what is needed.\n *\n * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained\n */\n function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);\n\n /**\n * Liquidate everything and returns the amount that got freed.\n * This function is used during emergency exit instead of `prepareReturn()` to\n * liquidate all of the Strategy's positions back to the Vault.\n */\n\n function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);\n\n /**\n * @notice\n * Provide a signal to the keeper that `tend()` should be called. The\n * keeper will provide the estimated gas cost that they would pay to call\n * `tend()`, and this function should use that estimate to make a\n * determination if calling it is \"worth it\" for the keeper. This is not\n * the only consideration into issuing this trigger, for example if the\n * position would be negatively affected if `tend()` is not called\n * shortly, then this can return `true` even if the keeper might be\n * \"at a loss\" (keepers are always reimbursed by Yearn).\n * @dev\n * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).\n *\n * This call and `harvestTrigger()` should never return `true` at the same\n * time.\n * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).\n * @return `true` if `tend()` should be called, `false` otherwise.\n */\n function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {\n // We usually don't need tend, but if there are positions that need\n // active maintainence, overriding this function is how you would\n // signal for that.\n // If your implementation uses the cost of the call in want, you can\n // use uint256 callCost = ethToWant(callCostInWei);\n\n return false;\n }\n\n /**\n * @notice\n * Adjust the Strategy's position. The purpose of tending isn't to\n * realize gains, but to maximize yield by reinvesting any returns.\n *\n * See comments on `adjustPosition()`.\n *\n * This may only be called by governance, the strategist, or the keeper.\n */\n function tend() external onlyKeepers {\n // Don't take profits with this call, but adjust for better gains\n adjustPosition(vault.debtOutstanding());\n }\n\n /**\n * @notice\n * Provide a signal to the keeper that `harvest()` should be called. The\n * keeper will provide the estimated gas cost that they would pay to call\n * `harvest()`, and this function should use that estimate to make a\n * determination if calling it is \"worth it\" for the keeper. This is not\n * the only consideration into issuing this trigger, for example if the\n * position would be negatively affected if `harvest()` is not called\n * shortly, then this can return `true` even if the keeper might be \"at a\n * loss\" (keepers are always reimbursed by Yearn).\n * @dev\n * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).\n *\n * This call and `tendTrigger` should never return `true` at the\n * same time.\n *\n * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the\n * strategist-controlled parameters that will influence whether this call\n * returns `true` or not. These parameters will be used in conjunction\n * with the parameters reported to the Vault (see `params`) to determine\n * if calling `harvest()` is merited.\n *\n * It is expected that an external system will check `harvestTrigger()`.\n * This could be a script run off a desktop or cloud bot (e.g.\n * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),\n * or via an integration with the Keep3r network (e.g.\n * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).\n * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).\n * @return `true` if `harvest()` should be called, `false` otherwise.\n */\n function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {\n uint256 callCost = ethToWant(callCostInWei);\n StrategyParams memory params = vault.strategies(address(this));\n\n // Should not trigger if Strategy is not activated\n if (params.activation == 0) return false;\n\n // Should not trigger if we haven't waited long enough since previous harvest\n if ((block.timestamp - params.lastReport) < minReportDelay) return false;\n\n // Should trigger if hasn't been called in a while\n if ((block.timestamp - params.lastReport) >= maxReportDelay) return true;\n\n // If some amount is owed, pay it back\n // NOTE: Since debt is based on deposits, it makes sense to guard against large\n // changes to the value from triggering a harvest directly through user\n // behavior. This should ensure reasonable resistance to manipulation\n // from user-initiated withdrawals as the outstanding debt fluctuates.\n uint256 outstanding = vault.debtOutstanding();\n if (outstanding > debtThreshold) return true;\n\n // Check for profits and losses\n uint256 total = estimatedTotalAssets();\n // Trigger if we have a loss to report\n if ((total + debtThreshold) < params.totalDebt) return true;\n\n uint256 profit = 0;\n if (total > params.totalDebt) profit = total - params.totalDebt; // We've earned a profit!\n\n // Otherwise, only trigger if it \"makes sense\" economically (gas cost\n // is <N% of value moved)\n uint256 credit = vault.creditAvailable();\n return ((profitFactor * callCost) < (credit + profit));\n }\n\n /**\n * @notice\n * Harvests the Strategy, recognizing any profits or losses and adjusting\n * the Strategy's position.\n *\n * In the rare case the Strategy is in emergency shutdown, this will exit\n * the Strategy's position.\n *\n * This may only be called by governance, the strategist, or the keeper.\n * @dev\n * When `harvest()` is called, the Strategy reports to the Vault (via\n * `vault.report()`), so in some cases `harvest()` must be called in order\n * to take in profits, to borrow newly available funds from the Vault, or\n * otherwise adjust its position. In other cases `harvest()` must be\n * called to report to the Vault on the Strategy's position, especially if\n * any losses have occurred.\n */\n function harvest() external onlyKeepers {\n uint256 profit = 0;\n uint256 loss = 0;\n uint256 debtOutstanding = vault.debtOutstanding();\n uint256 debtPayment = 0;\n if (emergencyExit) {\n // Free up as much capital as possible\n uint256 amountFreed = liquidateAllPositions();\n if (amountFreed < debtOutstanding) {\n loss = debtOutstanding - amountFreed;\n } else if (amountFreed > debtOutstanding) {\n profit = amountFreed - debtOutstanding;\n }\n debtPayment = debtOutstanding - loss;\n } else {\n // Free up returns for Vault to pull\n (profit, loss, debtPayment) = prepareReturn(debtOutstanding);\n }\n\n // Allow Vault to take up to the \"harvested\" balance of this contract,\n // which is the amount it has earned since the last time it reported to\n // the Vault.\n debtOutstanding = vault.report(profit, loss, debtPayment);\n\n // Check if free returns are left, and re-invest them\n adjustPosition(debtOutstanding);\n\n emit Harvested(profit, loss, debtPayment, debtOutstanding);\n }\n\n /**\n * @notice\n * Withdraws `_amountNeeded` to `vault`.\n *\n * This may only be called by the Vault.\n * @param _amountNeeded How much `want` to withdraw.\n * @return _loss Any realized losses\n */\n function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {\n require(msg.sender == address(vault), '!vault');\n // Liquidate as much as possible to `want`, up to `_amountNeeded`\n uint256 amountFreed;\n (amountFreed, _loss) = liquidatePosition(_amountNeeded);\n // Send it directly back (NOTE: Using `msg.sender` saves some gas here)\n SafeERC20.safeTransfer(want, msg.sender, amountFreed);\n // NOTE: Reinvest anything leftover on next `tend`/`harvest`\n }\n\n /**\n * Do anything necessary to prepare this Strategy for migration, such as\n * transferring any reserve or LP tokens, CDPs, or other tokens or stores of\n * value.\n */\n function prepareMigration(address _newStrategy) internal virtual;\n\n /**\n * @notice\n * Transfers all `want` from this Strategy to `_newStrategy`.\n *\n * This may only be called by the Vault.\n * @dev\n * The new Strategy's Vault must be the same as this Strategy's Vault.\n * The migration process should be carefully performed to make sure all\n * the assets are migrated to the new address, which should have never\n * interacted with the vault before.\n * @param _newStrategy The Strategy to migrate to.\n */\n function migrate(address _newStrategy) external {\n require(msg.sender == address(vault));\n require(BaseStrategy(_newStrategy).vault() == vault);\n prepareMigration(_newStrategy);\n SafeERC20.safeTransfer(want, _newStrategy, want.balanceOf(address(this)));\n }\n\n /**\n * @notice\n * Activates emergency exit. Once activated, the Strategy will exit its\n * position upon the next harvest, depositing all funds into the Vault as\n * quickly as is reasonable given on-chain conditions.\n *\n * This may only be called by governance or the strategist.\n * @dev\n * See `vault.setEmergencyShutdown()` and `harvest()` for further details.\n */\n function setEmergencyExit() external onlyEmergencyAuthorized {\n emergencyExit = true;\n vault.revokeStrategy();\n\n emit EmergencyExitEnabled();\n }\n\n /**\n * Override this to add all tokens/tokenized positions this contract\n * manages on a *persistent* basis (e.g. not just for swapping back to\n * want ephemerally).\n *\n * NOTE: Do *not* include `want`, already included in `sweep` below.\n *\n * Example:\n * ```\n * function protectedTokens() internal override view returns (address[] memory) {\n * address[] memory protected = new address[](3);\n * protected[0] = tokenA;\n * protected[1] = tokenB;\n * protected[2] = tokenC;\n * return protected;\n * }\n * ```\n */\n function protectedTokens() internal view virtual returns (address[] memory);\n\n /**\n