From b95032171d6b38cc432feca4a60314c3bab135d8 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Fri, 24 Apr 2026 12:49:31 -0600 Subject: [PATCH 01/27] build: instant acrual --- src/BaseStrategy.sol | 52 +- src/TokenizedStrategy.sol | 443 ++--- src/interfaces/IBaseStrategy.sol | 2 + src/interfaces/ITokenizedStrategy.sol | 8 +- src/test/Accounting.t.sol | 774 +++------ src/test/CustomImplementation.t.sol | 8 +- src/test/ERC20Std.t.sol | 54 +- src/test/ERC4626Std.t.sol | 1 + src/test/FaultyStrategy.t.sol | 329 +--- src/test/InvariantsSingleStrategy.t.sol | 8 - src/test/ProfitLocking.t.sol | 2059 +---------------------- src/test/Shutdown.t.sol | 8 +- src/test/e2e.t.sol | 2 +- src/test/mocks/MockFaultyStrategy.sol | 13 +- src/test/mocks/MockIlliquidStrategy.sol | 12 +- src/test/mocks/MockStorage.sol | 13 +- src/test/mocks/MockStrategy.sol | 10 +- src/test/utils/BaseInvariant.sol | 62 +- src/test/utils/Setup.sol | 1 - yarn.lock | 256 +-- 20 files changed, 773 insertions(+), 3342 deletions(-) diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 2622a88..4ecf794 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -22,7 +22,7 @@ import {ITokenizedStrategy} from "./interfaces/ITokenizedStrategy.sol"; * can only be concerned with writing their strategy specific code. * * This contract should be inherited and the three main abstract methods - * `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt + * `_deployFunds`, `_freeFunds` and `_totalAssets` implemented to adapt * the Strategy to the particular needs it has to generate yield. There are * other optional methods that can be implemented to further customize * the strategy if desired. @@ -203,31 +203,36 @@ abstract contract BaseStrategy { function _freeFunds(uint256 _amount) internal virtual; /** - * @dev Internal function to harvest all rewards, redeploy any idle - * funds and return an accurate accounting of all funds currently - * held by the Strategy. - * - * This should do any needed harvesting, rewards selling, accrual, - * redepositing etc. to get the most accurate view of current assets. + * @dev Internal function to return an accurate accounting of all funds + * currently held by the Strategy. * * NOTE: All applicable assets including loose assets should be * accounted for in this function. * - * Care should be taken when relying on oracles or swap values rather - * than actual amounts as all Strategy profit/loss accounting will - * be done based on this returned value. - * - * This can still be called post a shutdown, a strategist can check - * `TokenizedStrategy.isShutdown()` to decide if funds should be - * redeployed or simply realize any profits/losses. + * This function is used by ERC4626 view methods whenever the current block + * is not already latched, and by normal state changing accounting syncs + * when they refresh. It must be strictly read only and should not harvest, + * claim or otherwise mutate state. * * @return _totalAssets A trusted and accurate account for the total * amount of 'asset' the strategy currently holds including idle funds. */ + function _totalAssets() internal view virtual returns (uint256); + + /** + * @dev Internal hook used by explicit {report()} accounting syncs. + * + * This can harvest rewards, claim fees, realize external position changes + * or perform any other mutable work needed before returning the strategy's + * up-to-date total assets. + * + * @return _reportedAssets A trusted and accurate account for the total + * amount of 'asset' the strategy currently holds including idle funds. + */ function _harvestAndReport() internal virtual - returns (uint256 _totalAssets); + returns (uint256 _reportedAssets); /*////////////////////////////////////////////////////////////// OPTIONAL TO OVERRIDE BY STRATEGIST @@ -377,6 +382,23 @@ abstract contract BaseStrategy { _deployFunds(_amount); } + /** + * @notice Returns the strategies best current estimate for total assets. + * @dev Read-only callback for the TokenizedStrategy. + * + * This can only be called by this strategy during a delegate call flow so + * msg.sender must equal address(this). + */ + function strategyTotalAssets() + external + view + virtual + onlySelf + returns (uint256) + { + return _totalAssets(); + } + /** * @notice Should attempt to free the '_amount' of 'asset'. * @dev Callback for the TokenizedStrategy to call during a withdraw diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 61e5354..b57a3e8 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -217,23 +217,14 @@ contract TokenizedStrategy { mapping(address => uint256) nonces; // Mapping of nonces used for permit functions. mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares. mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. - - - // We manually track `totalAssets` to prevent PPS manipulation through airdrops. - uint256 totalAssets; - - - // Variables for profit reporting and locking. - // We use uint96 for timestamps to fit in the same slot as an address. That overflows in 2.5e+21 years. - // I know Yearn moves slowly but surely V4 will be out by then. - // If the timestamps ever overflow tell the cyborgs still using this code I'm sorry for being cheap. - uint256 profitUnlockingRate; // The rate at which locked profit is unlocking. - uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock. + // Last realized total assets. This is used as the accrual baseline during + // write flows and to freeze view math during in-flight external callbacks. + uint256 lastTotalAssets; address keeper; // Address given permission to call {report} and {tend}. - uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over. + uint32 profitMaxUnlockTime; uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. address performanceFeeRecipient; // The address to pay the `performanceFee` to. - uint96 lastReport; // The last time a {report} was called. + uint96 lastReport; // The last time accounting synced. // Access management variables. @@ -355,9 +346,6 @@ contract TokenizedStrategy { /// @notice Used for fee calculations. uint256 internal constant MAX_BPS = 10_000; - /// @notice Used for profit unlocking rate calculations. - uint256 internal constant MAX_BPS_EXTENDED = 1_000_000_000_000; - /// @notice Seconds per year for max profit unlocking time. uint256 internal constant SECONDS_PER_YEAR = 31_556_952; // 365.2425 days @@ -490,6 +478,7 @@ contract TokenizedStrategy { ) external nonReentrant returns (uint256 shares) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); + _accrue(S); // Deposit full balance if using max uint. if (assets == type(uint256).max) { @@ -523,6 +512,7 @@ contract TokenizedStrategy { ) external nonReentrant returns (uint256 assets) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); + _accrue(S); // Checking max mint will also check if shutdown. require(shares <= _maxMint(S, receiver), "ERC4626: mint more than max"); @@ -570,6 +560,7 @@ contract TokenizedStrategy { ) public nonReentrant returns (uint256 shares) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); + _accrue(S); require( assets <= _maxWithdraw(S, owner), "ERC4626: withdraw more than max" @@ -620,6 +611,7 @@ contract TokenizedStrategy { ) public nonReentrant returns (uint256) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); + _accrue(S); require( shares <= _maxRedeem(S, owner), "ERC4626: redeem more than max" @@ -641,9 +633,10 @@ contract TokenizedStrategy { /** * @notice Get the total amount of assets this strategy holds - * as of the last report. + * under the current block-latched accounting estimate. * - * We manually track `totalAssets` to avoid any PPS manipulation. + * Normal write flows freeze this value after the first sync in a block. + * A manual {report} can refresh it again within that same block. * * @return . Total assets the strategy holds. */ @@ -654,12 +647,6 @@ contract TokenizedStrategy { /** * @notice Get the current supply of the strategies shares. * - * Locked shares issued to the strategy from profits are not - * counted towards the full supply until they are unlocked. - * - * As more shares slowly unlock the totalSupply will decrease - * causing the PPS of the strategy to increase. - * * @return . Total amount of shares outstanding. */ function totalSupply() external view returns (uint256) { @@ -823,14 +810,65 @@ contract TokenizedStrategy { function _totalAssets( StrategyData storage S ) internal view returns (uint256) { - return S.totalAssets; + (, uint256 assets) = _simulatedTotals(S); + return assets; } /// @dev Internal implementation of {totalSupply}. function _totalSupply( StrategyData storage S ) internal view returns (uint256) { - return S.totalSupply - _unlockedShares(S); + return S.totalSupply; + } + + /// @dev Internal helper to simulate the supply/assets state under the current block latch. + function _simulatedTotals( + StrategyData storage S + ) internal view returns (uint256 supply, uint256 assets) { + supply = S.totalSupply; + + if (S.entered == ENTERED || block.timestamp == S.lastReport) { + return (supply, S.lastTotalAssets); + } + + assets = _strategyTotalAssets(); + if (assets <= S.lastTotalAssets) { + return (supply, assets); + } + + uint256 profit; + unchecked { + profit = assets - S.lastTotalAssets; + } + + if (S.lastTotalAssets == 0 && supply == 0) { + return (assets, assets); + } + + uint16 fee = S.performanceFee; + if (fee != 0 && supply != 0) { + uint256 totalFees = (profit * fee) / MAX_BPS; + if (totalFees != 0) { + supply += _feeSharesForAmount(S, totalFees, assets); + } + } + } + + /// @dev Internal helper to ask the strategy for its current total assets. + function _strategyTotalAssets() internal view returns (uint256) { + return IBaseStrategy(address(this)).strategyTotalAssets(); + } + + /// @dev Calculates shares that represent `assets` after fee minting dilution. + function _feeSharesForAmount( + StrategyData storage S, + uint256 assets, + uint256 totalAssets_ + ) internal view returns (uint256) { + uint256 supply = S.totalSupply; + if (assets == 0 || supply == 0) return 0; + + return assets.mulDiv(supply, totalAssets_ - assets, Math.Rounding.Down); } /// @dev Internal implementation of {convertToShares}. @@ -839,12 +877,10 @@ contract TokenizedStrategy { uint256 assets, Math.Rounding _rounding ) internal view returns (uint256) { - // Saves an extra SLOAD if values are non-zero. - uint256 totalSupply_ = _totalSupply(S); + (uint256 totalSupply_, uint256 totalAssets_) = _simulatedTotals(S); // If supply is 0, PPS = 1. if (totalSupply_ == 0) return assets; - uint256 totalAssets_ = _totalAssets(S); // If assets are 0 but supply is not PPS = 0. if (totalAssets_ == 0) return 0; @@ -857,13 +893,12 @@ contract TokenizedStrategy { uint256 shares, Math.Rounding _rounding ) internal view returns (uint256) { - // Saves an extra SLOAD if totalSupply() is non-zero. - uint256 supply = _totalSupply(S); + (uint256 supply, uint256 totalAssets_) = _simulatedTotals(S); return supply == 0 ? shares - : shares.mulDiv(_totalAssets(S), supply, _rounding); + : shares.mulDiv(totalAssets_, supply, _rounding); } /// @dev Internal implementation of {maxDeposit}. @@ -969,7 +1004,7 @@ contract TokenizedStrategy { ); // Adjust total Assets. - S.totalAssets += assets; + S.lastTotalAssets += assets; // mint shares _mint(S, receiver, shares); @@ -1036,7 +1071,7 @@ contract TokenizedStrategy { } // Update assets based on how much we took. - S.totalAssets -= (assets + loss); + S.lastTotalAssets -= (assets + loss); _burn(S, owner, shares); @@ -1049,243 +1084,127 @@ contract TokenizedStrategy { return assets; } - /*////////////////////////////////////////////////////////////// - PROFIT REPORTING - //////////////////////////////////////////////////////////////*/ + /// @dev Synchronize accounting using the strategy's current view estimate unless this block is already latched. + function _accrue( + StrategyData storage S + ) internal returns (uint256 profit, uint256 loss) { + return _accrue(S, _strategyTotalAssets(), false); + } /** - * @notice Function for keepers to call to harvest and record all - * profits accrued. - * - * @dev This will account for any gains/losses since the last report - * and charge fees accordingly. - * - * Any profit over the fees charged will be immediately locked - * so there is no change in PricePerShare. Then slowly unlocked - * over the `maxProfitUnlockTime` each second based on the - * calculated `profitUnlockingRate`. - * - * In case of a loss it will first attempt to offset the loss - * with any remaining locked shares from the last report in - * order to reduce any negative impact to PPS. - * - * Will then recalculate the new time to unlock profits over and the - * rate based on a weighted average of any remaining time from the - * last report and the new amount of shares to be locked. + * @dev Synchronize accounting to the strategy's latest asset balance and + * realize any accrued fees or losses. * - * @return profit The notional amount of gain if any since the last - * report in terms of `asset`. - * @return loss The notional amount of loss if any since the last - * report in terms of `asset`. + * When `force` is false this can only happen once per block. `report()` + * passes `force = true` so it can refresh accounting again intra-block. */ - function report() - external - nonReentrant - onlyKeepers - returns (uint256 profit, uint256 loss) - { - // Cache storage pointer since its used repeatedly. - StrategyData storage S = _strategyStorage(); - - // Tell the strategy to report the real total assets it has. - // It should do all reward selling and redepositing now and - // account for deployed and loose `asset` so we can accurately - // account for all funds including those potentially airdropped - // and then have any profits immediately locked. - uint256 newTotalAssets = IBaseStrategy(address(this)) - .harvestAndReport(); - - uint256 oldTotalAssets = _totalAssets(S); - - // Get the amount of shares we need to burn from previous reports. - uint256 sharesToBurn = _unlockedShares(S); + function _accrue( + StrategyData storage S, + uint256 newTotalAssets, + bool force + ) internal returns (uint256 profit, uint256 loss) { + if (!force && block.timestamp == S.lastReport) { + return (0, 0); + } - // Initialize variables needed throughout. + uint256 oldTotalAssets = S.lastTotalAssets; uint256 totalFees; uint256 protocolFees; - uint256 sharesToLock; - uint256 _profitMaxUnlockTime = S.profitMaxUnlockTime; - // Calculate profit/loss. + if (newTotalAssets > oldTotalAssets) { - // We have a profit. unchecked { profit = newTotalAssets - oldTotalAssets; } - // We need to get the equivalent amount of shares - // at the current PPS before any minting or burning. - sharesToLock = _convertToShares(S, profit, Math.Rounding.Down); + // Any assets that show up before the first depositor should not be + // claimable by that first depositor. Mint matching dead shares so + // the vault starts from a 1:1 PPS. + if (oldTotalAssets == 0 && S.totalSupply == 0) { + _mint(S, address(this), newTotalAssets); + } - // Cache the performance fee. uint16 fee = S.performanceFee; - uint256 totalFeeShares; - // If we are charging a performance fee - if (fee != 0) { - // Asses performance fees. - unchecked { - // Get in `asset` for the event. - totalFees = (profit * fee) / MAX_BPS; - // And in shares for the payment. - totalFeeShares = (sharesToLock * fee) / MAX_BPS; - } - - // Get the protocol fee config from the factory. - ( - uint16 protocolFeeBps, - address protocolFeesRecipient - ) = IFactory(FACTORY).protocol_fee_config(); - - uint256 protocolFeeShares; - // Check if there is a protocol fee to charge. - if (protocolFeeBps != 0) { - unchecked { - // Calculate protocol fees based on the performance Fees. - protocolFeeShares = - (totalFeeShares * protocolFeeBps) / - MAX_BPS; - // Need amount in underlying for event. - protocolFees = (totalFees * protocolFeeBps) / MAX_BPS; - } - - // Mint the protocol fees to the recipient. - _mint(S, protocolFeesRecipient, protocolFeeShares); - } + if (fee != 0 && oldTotalAssets != 0 && S.totalSupply != 0) { + totalFees = (profit * fee) / MAX_BPS; - // Mint the difference to the strategy fee recipient. - unchecked { - _mint( + if (totalFees != 0) { + uint256 totalFeeShares = _feeSharesForAmount( S, - S.performanceFeeRecipient, - totalFeeShares - protocolFeeShares + totalFees, + newTotalAssets ); - } - } - - // Check if we are locking profit. - if (_profitMaxUnlockTime != 0) { - // lock (profit - fees) - unchecked { - sharesToLock -= totalFeeShares; - } - // If we are burning more than re-locking. - if (sharesToBurn > sharesToLock) { - // Burn the difference - unchecked { - _burn(S, address(this), sharesToBurn - sharesToLock); - } - } else if (sharesToLock > sharesToBurn) { - // Mint the shares to lock the strategy. - unchecked { - _mint(S, address(this), sharesToLock - sharesToBurn); + if (totalFeeShares != 0) { + ( + uint16 protocolFeeBps, + address protocolFeesRecipient + ) = IFactory(FACTORY).protocol_fee_config(); + + uint256 protocolFeeShares; + if (protocolFeeBps != 0) { + protocolFees = + (totalFees * protocolFeeBps) / + MAX_BPS; + protocolFeeShares = + (totalFeeShares * protocolFeeBps) / + MAX_BPS; + + if (protocolFeeShares != 0) { + _mint( + S, + protocolFeesRecipient, + protocolFeeShares + ); + } + } + + unchecked { + _mint( + S, + S.performanceFeeRecipient, + totalFeeShares - protocolFeeShares + ); + } } } } - } else { - // Expect we have a loss. + } else if (oldTotalAssets > newTotalAssets) { unchecked { loss = oldTotalAssets - newTotalAssets; } - - // Check in case `else` was due to being equal. - if (loss != 0) { - // We will try and burn the unlocked shares and as much from any - // pending profit still unlocking to offset the loss to prevent any PPS decline post report. - sharesToBurn = Math.min( - // Cannot burn more than we have. - S.balances[address(this)], - // Try and burn both the shares already unlocked and the amount for the loss. - _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn - ); - } - - // Check if there is anything to burn. - if (sharesToBurn != 0) { - _burn(S, address(this), sharesToBurn); - } - } - - // Update unlocking rate and time to fully unlocked. - uint256 totalLockedShares = S.balances[address(this)]; - if (totalLockedShares != 0) { - uint256 previouslyLockedTime; - uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; - // Check if we need to account for shares still unlocking. - if (_fullProfitUnlockDate > block.timestamp) { - unchecked { - // There will only be previously locked shares if time remains. - // We calculate this here since it should be rare. - previouslyLockedTime = - (_fullProfitUnlockDate - block.timestamp) * - (totalLockedShares - sharesToLock); - } - } - - // newProfitLockingPeriod is a weighted average between the remaining - // time of the previously locked shares and the profitMaxUnlockTime. - uint256 newProfitLockingPeriod = (previouslyLockedTime + - sharesToLock * - _profitMaxUnlockTime) / totalLockedShares; - - // Calculate how many shares unlock per second. - S.profitUnlockingRate = - (totalLockedShares * MAX_BPS_EXTENDED) / - newProfitLockingPeriod; - - // Calculate how long until the full amount of shares is unlocked. - S.fullProfitUnlockDate = uint96( - block.timestamp + newProfitLockingPeriod - ); - } else { - // Only setting this to 0 will turn in the desired effect, - // no need to update profitUnlockingRate. - S.fullProfitUnlockDate = 0; } - // Update the new total assets value. - S.totalAssets = newTotalAssets; + S.lastTotalAssets = newTotalAssets; S.lastReport = uint96(block.timestamp); - // Emit event with info - emit Reported( - profit, - loss, - protocolFees, // Protocol fees - totalFees - protocolFees // Performance Fees - ); + emit Reported(profit, loss, protocolFees, totalFees - protocolFees); } - /** - * @notice Get how many shares have been unlocked since last report. - * @return . The amount of shares that have unlocked. - */ - function unlockedShares() external view returns (uint256) { - return _unlockedShares(_strategyStorage()); - } + /*////////////////////////////////////////////////////////////// + PROFIT REPORTING + //////////////////////////////////////////////////////////////*/ /** - * @dev To determine how many of the shares that were locked during the last - * report have since unlocked. + * @notice Function for keepers to synchronize accounting to the latest + * strategy asset balance. * - * If the `fullProfitUnlockDate` has passed the full strategy's balance will - * count as unlocked. + * @dev This will account for any gains/losses since the last sync and + * charge fees accordingly. * - * @return unlocked The amount of shares that have unlocked. + * @return profit The notional amount of gain if any since the last + * report in terms of `asset`. + * @return loss The notional amount of loss if any since the last + * report in terms of `asset`. */ - function _unlockedShares( - StrategyData storage S - ) internal view returns (uint256 unlocked) { - uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; - if (_fullProfitUnlockDate > block.timestamp) { - unchecked { - unlocked = - (S.profitUnlockingRate * (block.timestamp - S.lastReport)) / - MAX_BPS_EXTENDED; - } - } else if (_fullProfitUnlockDate != 0) { - // All shares have been unlocked. - unlocked = S.balances[address(this)]; - } + function report() + external + nonReentrant + onlyKeepers + returns (uint256 profit, uint256 loss) + { + StrategyData storage S = _strategyStorage(); + return + _accrue(S, IBaseStrategy(address(this)).harvestAndReport(), true); } /*////////////////////////////////////////////////////////////// @@ -1432,23 +1351,6 @@ contract TokenizedStrategy { return _strategyStorage().performanceFeeRecipient; } - /** - * @notice Gets the timestamp at which all profits will be unlocked. - * @return . The full profit unlocking timestamp - */ - function fullProfitUnlockDate() external view returns (uint256) { - return uint256(_strategyStorage().fullProfitUnlockDate); - } - - /** - * @notice The per second rate at which profits are unlocking. - * @dev This is denominated in EXTENDED_BPS decimals. - * @return . The current profit unlocking rate. - */ - function profitUnlockingRate() external view returns (uint256) { - return _strategyStorage().profitUnlockingRate; - } - /** * @notice Gets the current time profits are set to unlock over. * @return . The current profit max unlock time. @@ -1458,13 +1360,21 @@ contract TokenizedStrategy { } /** - * @notice The timestamp of the last time protocol fees were charged. + * @notice The timestamp of the last accounting sync. * @return . The last report. */ function lastReport() external view returns (uint256) { return uint256(_strategyStorage().lastReport); } + /** + * @notice The last realized total assets baseline. + * @return . The last stored total assets. + */ + function lastTotalAssets() external view returns (uint256) { + return _strategyStorage().lastTotalAssets; + } + /** * @notice Get the price per share. * @dev This value offers limited precision. Integrations that require @@ -1555,6 +1465,7 @@ contract TokenizedStrategy { * @param _performanceFee New performance fee. */ function setPerformanceFee(uint16 _performanceFee) external onlyManagement { + _accrue(_strategyStorage()); require(_performanceFee <= MAX_FEE, "MAX FEE"); _strategyStorage().performanceFee = _performanceFee; @@ -1572,6 +1483,7 @@ contract TokenizedStrategy { function setPerformanceFeeRecipient( address _performanceFeeRecipient ) external onlyManagement { + _accrue(_strategyStorage()); require(_performanceFeeRecipient != address(0), "ZERO ADDRESS"); require(_performanceFeeRecipient != address(this), "Cannot be self"); _strategyStorage().performanceFeeRecipient = _performanceFeeRecipient; @@ -1598,21 +1510,7 @@ contract TokenizedStrategy { ) external onlyManagement { // Must be less than a year. require(_profitMaxUnlockTime <= SECONDS_PER_YEAR, "too long"); - StrategyData storage S = _strategyStorage(); - - // If we are setting to 0 we need to adjust amounts. - if (_profitMaxUnlockTime == 0) { - uint256 shares = S.balances[address(this)]; - if (shares != 0) { - // Burn all shares if applicable. - _burn(S, address(this), shares); - } - // Reset unlocking variables - S.profitUnlockingRate = 0; - S.fullProfitUnlockDate = 0; - } - - S.profitMaxUnlockTime = uint32(_profitMaxUnlockTime); + _strategyStorage().profitMaxUnlockTime = uint32(_profitMaxUnlockTime); emit UpdateProfitMaxUnlockTime(_profitMaxUnlockTime); } @@ -1657,8 +1555,6 @@ contract TokenizedStrategy { /** * @notice Returns the current balance for a given '_account'. - * @dev If the '_account` is the strategy then this will subtract - * the amount of shares that have been unlocked since the last profit first. * @param account the address to return the balance for. * @return . The current balance in y shares of the '_account'. */ @@ -1671,9 +1567,6 @@ contract TokenizedStrategy { StrategyData storage S, address account ) internal view returns (uint256) { - if (account == address(this)) { - return S.balances[account] - _unlockedShares(S); - } return S.balances[account]; } diff --git a/src/interfaces/IBaseStrategy.sol b/src/interfaces/IBaseStrategy.sol index a76dd50..9a3e007 100644 --- a/src/interfaces/IBaseStrategy.sol +++ b/src/interfaces/IBaseStrategy.sol @@ -16,6 +16,8 @@ interface IBaseStrategy { address _owner ) external view returns (uint256); + function strategyTotalAssets() external view returns (uint256); + function deployFunds(uint256 _assets) external; function freeFunds(uint256 _amount) external; diff --git a/src/interfaces/ITokenizedStrategy.sol b/src/interfaces/ITokenizedStrategy.sol index a201d89..b1cbaf1 100644 --- a/src/interfaces/ITokenizedStrategy.sol +++ b/src/interfaces/ITokenizedStrategy.sol @@ -128,17 +128,13 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { function performanceFeeRecipient() external view returns (address); - function fullProfitUnlockDate() external view returns (uint256); - - function profitUnlockingRate() external view returns (uint256); - function profitMaxUnlockTime() external view returns (uint256); function lastReport() external view returns (uint256); - function isShutdown() external view returns (bool); + function lastTotalAssets() external view returns (uint256); - function unlockedShares() external view returns (uint256); + function isShutdown() external view returns (bool); /*////////////////////////////////////////////////////////////// SETTERS diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index c0ea7a6..9eb24bc 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -1,700 +1,336 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.18; -import "forge-std/console.sol"; -import {Setup, IMockStrategy} from "./utils/Setup.sol"; +import {Setup} from "./utils/Setup.sol"; contract AccountingTest is Setup { function setUp() public override { super.setUp(); } - function test_airdropDoesNotIncreasePPS( - address _address, + function test_airdropImmediatelyAccruesInViews( + address _user, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) ); - // set fees to 0 for calculations simplicity setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); - // nothing has happened pps should be 1 - uint256 pricePerShare = strategy.pricePerShare(); - assertEq(pricePerShare, wad); + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 pps = strategy.pricePerShare(); - // deposit into the vault - mintAndDepositIntoStrategy(strategy, _address, _amount); + asset.mint(address(strategy), profit); - // should still be 1 - assertEq(strategy.pricePerShare(), pricePerShare); + assertEq(strategy.totalAssets(), _amount, "!assets frozen"); + assertEq(strategy.pricePerShare(), pps, "!pps frozen"); - // airdrop to strategy - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(strategy), toAirdrop); + skip(1); - // PPS shouldn't change but the balance does. - assertEq(strategy.pricePerShare(), pricePerShare); - checkStrategyTotals( - strategy, - _amount, - _amount - toAirdrop, - toAirdrop, - _amount - ); + assertEq(strategy.totalAssets(), _amount + profit, "!assets"); + assertGt(strategy.pricePerShare(), pps, "!pps"); + + uint256 before = asset.balanceOf(_user); + + uint256 shares = strategy.balanceOf(_user); - uint256 beforeBalance = asset.balanceOf(_address); - vm.prank(_address); - strategy.redeem(_amount, _address, _address); + vm.prank(_user); + strategy.redeem(shares, _user, _user); - // should have pulled out just the deposited amount leaving the rest deployed. - assertEq(asset.balanceOf(_address), beforeBalance + _amount); - assertEq(asset.balanceOf(address(strategy)), 0); - assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); + assertEq(asset.balanceOf(_user) - before, _amount + profit, "!out"); checkStrategyTotals(strategy, 0, 0, 0, 0); } - function test_airdropDoesNotIncreasePPS_reportRecordsIt( - address _address, + function test_yieldSourceGainImmediatelyAccruesInViews( + address _user, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) ); - // set fees to 0 for calculations simplicity setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); - // nothing has happened pps should be 1 - uint256 pricePerShare = strategy.pricePerShare(); - assertEq(pricePerShare, wad); - - // deposit into the vault - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // should still be 1 - assertEq(strategy.pricePerShare(), pricePerShare); - - // airdrop to strategy - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(strategy), toAirdrop); - - // PPS shouldn't change but the balance does. - assertEq(strategy.pricePerShare(), pricePerShare); - checkStrategyTotals( - strategy, - _amount, - _amount - toAirdrop, - toAirdrop, - _amount - ); - - // process a report to realize the gain from the airdrop - uint256 profit; - vm.prank(keeper); - (profit, ) = strategy.report(); - - assertEq(strategy.pricePerShare(), pricePerShare); - assertEq(profit, toAirdrop); - checkStrategyTotals( - strategy, - _amount + toAirdrop, - _amount + toAirdrop, - 0, - _amount + toAirdrop - ); + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 pps = strategy.pricePerShare(); - // allow some profit to come unlocked - skip(profitMaxUnlockTime / 2); + asset.mint(address(yieldSource), profit); - assertGt(strategy.pricePerShare(), pricePerShare); + assertEq(strategy.totalAssets(), _amount, "!assets frozen"); + assertEq(strategy.pricePerShare(), pps, "!pps frozen"); - //air drop again, we should not increase again - pricePerShare = strategy.pricePerShare(); - asset.mint(address(strategy), toAirdrop); - assertEq(strategy.pricePerShare(), pricePerShare); + skip(1); - // skip the rest of the time for unlocking - skip(profitMaxUnlockTime / 2); + assertEq(strategy.totalAssets(), _amount + profit, "!assets"); + assertGt(strategy.pricePerShare(), pps, "!pps"); - // we should get a % return equal to our profit factor - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); + uint256 before = asset.balanceOf(_user); - // Total is the same but balance has adjusted again - checkStrategyTotals(strategy, _amount + toAirdrop, _amount, toAirdrop); + uint256 shares = strategy.balanceOf(_user); - uint256 beforeBalance = asset.balanceOf(_address); - vm.prank(_address); - strategy.redeem(_amount, _address, _address); + vm.prank(_user); + strategy.redeem(shares, _user, _user); - // should have pulled out the deposit plus profit that was reported but not the second airdrop - assertEq( - asset.balanceOf(_address), - beforeBalance + _amount + toAirdrop - ); - assertEq(asset.balanceOf(address(strategy)), 0); - assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); + assertEq(asset.balanceOf(_user) - before, _amount + profit, "!out"); checkStrategyTotals(strategy, 0, 0, 0, 0); } - function test_earningYieldDoesNotIncreasePPS( - address _address, + function test_previewDepositMatchesSyncAfterAccruedFees( + address _user, + address _depositor, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _depositor != address(0) && + _user != _depositor && + _user != address(strategy) && + _depositor != address(strategy) && + _user != keeper && + _depositor != keeper && + _user != management && + _depositor != management && + _user != emergencyAdmin && + _depositor != emergencyAdmin && + _user != protocolFeeRecipient && + _depositor != protocolFeeRecipient && + _user != performanceFeeRecipient && + _depositor != performanceFeeRecipient && + _user != address(yieldSource) && + _depositor != address(yieldSource) ); - // set fees to 0 for calculations simplicity - setFees(0, 0); - - // nothing has happened pps should be 1 - uint256 pricePerShare = strategy.pricePerShare(); - assertEq(pricePerShare, wad); + uint16 performanceFee = 1_000; + setFees(0, performanceFee); + mintAndDepositIntoStrategy(strategy, _user, _amount); - // deposit into the strategy - mintAndDepositIntoStrategy(strategy, _address, _amount); + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedFeeAssets = (profit * performanceFee) / MAX_BPS; + asset.mint(address(strategy), profit); - // should still be 1 - assertEq(strategy.pricePerShare(), pricePerShare); + skip(1); - // airdrop to strategy - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(yieldSource), toAirdrop); + uint256 preview = strategy.previewDeposit(_amount); - // nothing should change - assertEq(strategy.pricePerShare(), pricePerShare); - checkStrategyTotals(strategy, _amount, _amount, 0, _amount); + asset.mint(_depositor, _amount); + vm.prank(_depositor); + asset.approve(address(strategy), _amount); - uint256 beforeBalance = asset.balanceOf(_address); - vm.prank(_address); - strategy.redeem(_amount, _address, _address); + vm.prank(_depositor); + uint256 minted = strategy.deposit(_amount, _depositor); - // should have pulled out just the deposit amount - assertEq(asset.balanceOf(_address), beforeBalance + _amount); - assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); - checkStrategyTotals(strategy, 0, 0, 0, 0); + assertEq(minted, preview, "!preview"); + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedFeeAssets, + 100 + ); } - function test_earningYieldDoesNotIncreasePPS_reportRecordsIt( - address _address, + function test_reportReturnsZeroAfterWriteSync( + address _user, + address _depositor, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - // set fees to 0 for calculations simplicity - setFees(0, 0); - - // nothing has happened pps should be 1 - uint256 pricePerShare = strategy.pricePerShare(); - assertEq(pricePerShare, wad); - - // deposit into the vault - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // should still be 1 - assertEq(strategy.pricePerShare(), pricePerShare); - - // airdrop to strategy - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(yieldSource), toAirdrop); - assertEq(asset.balanceOf(address(yieldSource)), _amount + toAirdrop); - - // nothing should change - assertEq(strategy.pricePerShare(), pricePerShare); - checkStrategyTotals(strategy, _amount, _amount, 0, _amount); - - // process a report to realize the gain from the airdrop - uint256 profit; - vm.prank(keeper); - (profit, ) = strategy.report(); - - assertEq(strategy.pricePerShare(), pricePerShare); - assertEq(profit, toAirdrop); - - checkStrategyTotals( - strategy, - _amount + toAirdrop, - _amount + toAirdrop, - 0, - _amount + toAirdrop - ); - - // allow some profit to come unlocked - skip(profitMaxUnlockTime / 2); - - assertGt(strategy.pricePerShare(), pricePerShare); - - //air drop again, we should not increase again - pricePerShare = strategy.pricePerShare(); - asset.mint(address(yieldSource), toAirdrop); - assertEq(strategy.pricePerShare(), pricePerShare); - - // skip the rest of the time for unlocking - skip(profitMaxUnlockTime / 2); - - // we should get a % return equal to our profit factor - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - // Total is the same. - checkStrategyTotals( - strategy, - _amount + toAirdrop, - _amount + toAirdrop, - 0 - ); - - uint256 beforeBalance = asset.balanceOf(_address); - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - // should have pulled out the deposit plus profit that was reported but not the second airdrop - assertEq( - asset.balanceOf(_address), - beforeBalance + _amount + toAirdrop + _user != address(0) && + _depositor != address(0) && + _user != _depositor && + _user != address(strategy) && + _depositor != address(strategy) && + _user != keeper && + _depositor != keeper && + _user != management && + _depositor != management && + _user != emergencyAdmin && + _depositor != emergencyAdmin && + _user != protocolFeeRecipient && + _depositor != protocolFeeRecipient && + _user != performanceFeeRecipient && + _depositor != performanceFeeRecipient && + _user != address(yieldSource) && + _depositor != address(yieldSource) ); - assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); - checkStrategyTotals(strategy, 0, 0, 0, 0); - } - - function test_tend_noIdle_harvestProfit( - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 1, MAX_BPS)); - setFees(0, 0); - // nothing has happened pps should be 1 - uint256 pricePerShare = strategy.pricePerShare(); - assertEq(pricePerShare, wad); + mintAndDepositIntoStrategy(strategy, _user, _amount); - // deposit into the vault - mintAndDepositIntoStrategy(strategy, user, _amount); + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), profit); - // should still be 1 - assertEq(strategy.pricePerShare(), pricePerShare); + skip(1); - // airdrop to strategy to simulate a harvesting of rewards - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(strategy), toAirdrop); - assertEq(asset.balanceOf(address(strategy)), toAirdrop); - checkStrategyTotals(strategy, _amount, _amount - toAirdrop, toAirdrop); + asset.mint(_depositor, _amount); + vm.prank(_depositor); + asset.approve(address(strategy), _amount); - vm.prank(keeper); - strategy.tend(); - - // Should have deposited the toAirdrop amount but no other changes - checkStrategyTotals(strategy, _amount, _amount, 0); - assertEq( - asset.balanceOf(address(yieldSource)), - _amount + toAirdrop, - "!yieldSource" - ); - assertEq(strategy.pricePerShare(), wad, "!pps"); + vm.prank(_depositor); + strategy.deposit(_amount, _depositor); - // Make sure we now report the profit correctly vm.prank(keeper); - strategy.report(); - - skip(profitMaxUnlockTime); - - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - uint256 beforeBalance = asset.balanceOf(user); - vm.prank(user); - strategy.redeem(_amount, user, user); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); - // should have pulled out the deposit plus profit that was reported but not the second airdrop - assertEq(asset.balanceOf(user), beforeBalance + _amount + toAirdrop); - assertEq(asset.balanceOf(address(yieldSource)), 0); - checkStrategyTotals(strategy, 0, 0, 0, 0); + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); } - function test_tend_idleFunds_harvestProfit( + function test_settingFeeSyncsExistingProfit( + address _user, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 1, MAX_BPS)); - - // Use the illiquid mock strategy so it doesn't deposit all funds - strategy = IMockStrategy(setUpIlliquidStrategy()); - - setFees(0, 0); - // nothing has happened pps should be 1 - uint256 pricePerShare = strategy.pricePerShare(); - assertEq(pricePerShare, wad); - - // deposit into the vault - mintAndDepositIntoStrategy(strategy, user, _amount); - - uint256 expectedDeposit = _amount / 2; - checkStrategyTotals( - strategy, - _amount, - expectedDeposit, - _amount - expectedDeposit, - _amount - ); - - assertEq( - asset.balanceOf(address(yieldSource)), - expectedDeposit, - "!yieldSource" - ); - // should still be 1 - assertEq(strategy.pricePerShare(), wad); - - // airdrop to strategy to simulate a harvesting of rewards - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(strategy), toAirdrop); - assertEq( - asset.balanceOf(address(strategy)), - _amount - expectedDeposit + toAirdrop - ); - - vm.prank(keeper); - strategy.tend(); - - // Should have withdrawn all the funds from the yield source - checkStrategyTotals(strategy, _amount, 0, _amount, _amount); - assertEq(asset.balanceOf(address(yieldSource)), 0, "!yieldSource"); - assertEq(asset.balanceOf(address(strategy)), _amount + toAirdrop); - assertEq(strategy.pricePerShare(), wad, "!pps"); - - // Make sure we now report the profit correctly - vm.prank(keeper); - strategy.report(); - - checkStrategyTotals( - strategy, - _amount + toAirdrop, - (_amount + toAirdrop) / 2, - (_amount + toAirdrop) - ((_amount + toAirdrop) / 2) - ); - assertEq( - asset.balanceOf(address(yieldSource)), - (_amount + toAirdrop) / 2 - ); - - skip(profitMaxUnlockTime); - - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - } - - function test_withdrawWithUnrealizedLoss_reverts( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - uint256 toLose = (_amount * _lossFactor) / MAX_BPS; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); - - vm.expectRevert("too much loss"); - vm.prank(_address); - strategy.withdraw(_amount, _address, _address); - } - - function test_withdrawWithUnrealizedLoss_withMaxLoss( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) ); - setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - uint256 toLose = (_amount * _lossFactor) / MAX_BPS; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); + uint16 performanceFee = 1_000; + setFees(0, performanceFee); + mintAndDepositIntoStrategy(strategy, _user, _amount); - uint256 beforeBalance = asset.balanceOf(_address); - uint256 expectedOut = _amount - toLose; - // Withdraw the full amount before the loss is reported. - vm.prank(_address); - strategy.withdraw(_amount, _address, _address, _lossFactor); + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedFeeAssets = (profit * performanceFee) / MAX_BPS; + asset.mint(address(strategy), profit); - uint256 afterBalance = asset.balanceOf(_address); + skip(1); - assertEq(afterBalance - beforeBalance, expectedOut); - assertEq(strategy.pricePerShare(), wad); - checkStrategyTotals(strategy, 0, 0, 0, 0); - } + vm.prank(management); + strategy.setPerformanceFee(0); - function test_redeemWithUnrealizedLoss( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + assertEq(strategy.performanceFee(), 0, "!fee"); + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedFeeAssets, + 100 ); - - setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - uint256 toLose = (_amount * _lossFactor) / MAX_BPS; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); - - uint256 beforeBalance = asset.balanceOf(_address); - uint256 expectedOut = _amount - toLose; - // Withdraw the full amount before the loss is reported. - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 afterBalance = asset.balanceOf(_address); - - assertEq(afterBalance - beforeBalance, expectedOut); - assertEq(strategy.pricePerShare(), wad); - checkStrategyTotals(strategy, 0, 0, 0, 0); } - function test_redeemWithUnrealizedLoss_allowNoLoss_reverts( - address _address, + function test_lossHitsViewsImmediately( + address _user, uint256 _amount, uint16 _lossFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, 5_000)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) ); setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); + mintAndDepositIntoStrategy(strategy, _user, _amount); - uint256 toLose = (_amount * _lossFactor) / MAX_BPS; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + yieldSource.simulateLoss(loss); - vm.expectRevert("too much loss"); - vm.prank(_address); - strategy.redeem(_amount, _address, _address, 0); - } + assertEq(strategy.totalAssets(), _amount, "!assets frozen"); + assertEq(strategy.maxWithdraw(_user), _amount, "!withdraw frozen"); - function test_redeemWithUnrealizedLoss_customMaxLoss( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - uint256 toLose = (_amount * _lossFactor) / MAX_BPS; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); - - uint256 beforeBalance = asset.balanceOf(_address); - uint256 expectedOut = _amount - toLose; - - // First set it to just under the expected loss. - vm.expectRevert("too much loss"); - vm.prank(_address); - strategy.redeem(_amount, _address, _address, _lossFactor - 1); - - // Now redeem with the correct loss. - vm.prank(_address); - strategy.redeem(_amount, _address, _address, _lossFactor); - - uint256 afterBalance = asset.balanceOf(_address); - - assertEq(afterBalance - beforeBalance, expectedOut); - assertEq(strategy.pricePerShare(), wad); - checkStrategyTotals(strategy, 0, 0, 0, 0); - } - - function test_maxUintDeposit_depositsBalance( - address _address, - uint256 _amount - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - asset.mint(_address, _amount); - - vm.prank(_address); - asset.approve(address(strategy), _amount); - - assertEq(asset.balanceOf(_address), _amount); + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); - vm.prank(_address); - strategy.deposit(type(uint256).max, _address); + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, loss, "!loss"); + assertEq(strategy.totalAssets(), _amount - loss, "!assets"); + assertEq(strategy.maxWithdraw(_user), _amount - loss, "!withdraw"); - // Should just deposit the available amount. - checkStrategyTotals(strategy, _amount, _amount, 0, _amount); + uint256 before = asset.balanceOf(_user); + uint256 shares = strategy.balanceOf(_user); - assertEq(asset.balanceOf(_address), 0); - assertEq(strategy.balanceOf(_address), _amount); - assertEq(asset.balanceOf(address(strategy)), 0); + vm.prank(_user); + uint256 assets = strategy.redeem(shares, _user, _user); - assertEq(asset.balanceOf(address(yieldSource)), _amount); + assertEq(assets, _amount - loss, "!redeem"); + assertEq(asset.balanceOf(_user) - before, _amount - loss, "!out"); } - function test_deposit_zeroAssetsPositiveSupply_reverts( - address _address, - uint256 _amount + function test_initialDonationMintsDeadShares( + address _user, + uint256 _amount, + uint256 _donation ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _donation = bound(_donation, minFuzzAmount, maxFuzzAmount); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) ); setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - uint256 toLose = _amount; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); + skip(1); - vm.prank(keeper); - strategy.report(); + asset.mint(address(strategy), _donation); - // Should still have shares but no assets - checkStrategyTotals(strategy, 0, 0, 0, _amount); + assertEq(strategy.previewDeposit(_amount), _amount, "!preview"); - assertEq(strategy.balanceOf(_address), _amount); - assertEq(asset.balanceOf(address(strategy)), 0); - assertEq(asset.balanceOf(address(yieldSource)), 0); - - asset.mint(_address, _amount); - vm.prank(_address); - asset.approve(address(strategy), _amount); + mintAndDepositIntoStrategy(strategy, _user, _amount); - vm.expectRevert("ZERO_SHARES"); - vm.prank(_address); - strategy.deposit(_amount, _address); + assertEq(strategy.balanceOf(_user), _amount, "!shares"); + assertEq(strategy.balanceOf(address(strategy)), _donation, "!dead"); + assertEq(strategy.totalAssets(), _amount + _donation, "!assets"); - assertEq(strategy.convertToAssets(_amount), 0); - assertEq(strategy.convertToShares(_amount), 0); - assertEq(strategy.pricePerShare(), 0); - } + uint256 before = asset.balanceOf(_user); - function test_mint_zeroAssetsPositiveSupply_reverts( - address _address, - uint256 _amount - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - setFees(0, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - uint256 toLose = _amount; - // Simulate a loss. - vm.prank(address(yieldSource)); - asset.transfer(address(69), toLose); - - vm.prank(keeper); - strategy.report(); - - // Should still have shares but no assets - checkStrategyTotals(strategy, 0, 0, 0, _amount); - - assertEq(strategy.balanceOf(_address), _amount); - assertEq(asset.balanceOf(address(strategy)), 0); - assertEq(asset.balanceOf(address(yieldSource)), 0); - - asset.mint(_address, _amount); - vm.prank(_address); - asset.approve(address(strategy), _amount); + uint256 shares = strategy.balanceOf(_user); - vm.expectRevert("ZERO_ASSETS"); - vm.prank(_address); - strategy.mint(_amount, _address); + vm.prank(_user); + strategy.redeem(shares, _user, _user); - assertEq(strategy.convertToAssets(_amount), 0); - assertEq(strategy.convertToShares(_amount), 0); - assertEq(strategy.pricePerShare(), 0); + assertEq(asset.balanceOf(_user) - before, _amount, "!out"); + assertEq(strategy.totalAssets(), _donation, "!remaining"); } } diff --git a/src/test/CustomImplementation.t.sol b/src/test/CustomImplementation.t.sol index ac36be1..78c582d 100644 --- a/src/test/CustomImplementation.t.sol +++ b/src/test/CustomImplementation.t.sol @@ -54,9 +54,7 @@ contract CustomImplementationsTest is Setup { vm.prank(_address); strategy.withdraw(_amount, _address, _address); - createAndCheckProfit(strategy, profit, 0, 0); - - increaseTimeAndCheckBuffer(strategy, 5 days, profit / 2); + asset.mint(address(yieldSource), profit); idle = asset.balanceOf(address(strategy)); assertGt(idle, 0); @@ -148,9 +146,7 @@ contract CustomImplementationsTest is Setup { vm.prank(_address); strategy.withdraw(_amount, _address, _address); - createAndCheckProfit(strategy, profit, 0, 0); - - increaseTimeAndCheckBuffer(strategy, 5 days, profit / 2); + asset.mint(address(yieldSource), profit); idle = asset.balanceOf(address(strategy)); assertGt(idle, 0); diff --git a/src/test/ERC20Std.t.sol b/src/test/ERC20Std.t.sol index d8103f8..08ba404 100644 --- a/src/test/ERC20Std.t.sol +++ b/src/test/ERC20Std.t.sol @@ -27,7 +27,11 @@ contract ERC20BaseTest is Setup { } function testFuzz_mint(address account_, uint256 amount_) public { - vm.assume(account_ != address(0) && account_ != address(strategy)); + vm.assume( + account_ != address(0) && + account_ != address(strategy) && + account_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); vm.prank(address(strategy)); @@ -42,7 +46,11 @@ contract ERC20BaseTest is Setup { uint256 amount0_, uint256 amount1_ ) public { - vm.assume(account_ != address(0) && account_ != address(strategy)); + vm.assume( + account_ != address(0) && + account_ != address(strategy) && + account_ != address(yieldSource) + ); amount0_ = bound(amount0_, minFuzzAmount + 1, maxFuzzAmount); amount1_ = bound(amount1_, minFuzzAmount, amount0_); @@ -55,7 +63,11 @@ contract ERC20BaseTest is Setup { } function testFuzz_approve(address account_, uint256 amount_) public { - vm.assume(account_ != address(0) && account_ != address(strategy)); + vm.assume( + account_ != address(0) && + account_ != address(strategy) && + account_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); assertTrue(strategy.approve(account_, amount_)); @@ -64,7 +76,11 @@ contract ERC20BaseTest is Setup { } function testFuzz_transfer(address account_, uint256 amount_) public { - vm.assume(account_ != address(0) && account_ != address(strategy)); + vm.assume( + account_ != address(0) && + account_ != address(strategy) && + account_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); mintAndDepositIntoStrategy(strategy, self, amount_); @@ -86,7 +102,11 @@ contract ERC20BaseTest is Setup { uint256 approval_, uint256 amount_ ) public { - vm.assume(recipient_ != address(0) && recipient_ != address(strategy)); + vm.assume( + recipient_ != address(0) && + recipient_ != address(strategy) && + recipient_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); approval_ = bound(approval_, amount_, type(uint256).max - 1); @@ -117,7 +137,11 @@ contract ERC20BaseTest is Setup { address recipient_, uint256 amount_ ) public { - vm.assume(recipient_ != address(0) && recipient_ != address(strategy)); + vm.assume( + recipient_ != address(0) && + recipient_ != address(strategy) && + recipient_ != address(yieldSource) + ); uint256 MAX_UINT256 = type(uint256).max; amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); @@ -148,7 +172,11 @@ contract ERC20BaseTest is Setup { address recipient_, uint256 amount_ ) public { - vm.assume(recipient_ != address(0) && recipient_ != address(strategy)); + vm.assume( + recipient_ != address(0) && + recipient_ != address(strategy) && + recipient_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); ERC20User account = new ERC20User(); @@ -168,7 +196,11 @@ contract ERC20BaseTest is Setup { address recipient_, uint256 amount_ ) public { - vm.assume(recipient_ != address(0) && recipient_ != address(strategy)); + vm.assume( + recipient_ != address(0) && + recipient_ != address(strategy) && + recipient_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); ERC20User owner = new ERC20User(); @@ -190,7 +222,11 @@ contract ERC20BaseTest is Setup { address recipient_, uint256 amount_ ) public { - vm.assume(recipient_ != address(0) && recipient_ != address(strategy)); + vm.assume( + recipient_ != address(0) && + recipient_ != address(strategy) && + recipient_ != address(yieldSource) + ); amount_ = bound(amount_, minFuzzAmount, maxFuzzAmount); ERC20User owner = new ERC20User(); diff --git a/src/test/ERC4626Std.t.sol b/src/test/ERC4626Std.t.sol index 95506a3..38edd45 100644 --- a/src/test/ERC4626Std.t.sol +++ b/src/test/ERC4626Std.t.sol @@ -9,6 +9,7 @@ import {Setup} from "./utils/Setup.sol"; contract ERC4626StdTest is ERC4626Test, Setup { function setUp() public override(ERC4626Test, Setup) { super.setUp(); + setFees(0, 0); _underlying_ = address(asset); _vault_ = address(strategy); _delta_ = 0; diff --git a/src/test/FaultyStrategy.t.sol b/src/test/FaultyStrategy.t.sol index 70720e3..15a373b 100644 --- a/src/test/FaultyStrategy.t.sol +++ b/src/test/FaultyStrategy.t.sol @@ -1,16 +1,13 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.18; -import "forge-std/console.sol"; import {Setup, IMockStrategy} from "./utils/Setup.sol"; contract FaultyStrategy is Setup { - // Full reentrancy variables bool public reenter; address public addr; uint256 public amount; - // View reentrancy variables uint256 public pps; uint256 public convertAmountToShares; uint256 public convertAmountToAssets; @@ -19,282 +16,119 @@ contract FaultyStrategy is Setup { super.setUp(); } - function test_faultyStrategy_depositsToMuch( - address _address, - uint256 _amount, - uint256 _faultAmount - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _faultAmount = bound(_faultAmount, 10, MAX_BPS); - - strategy = IMockStrategy(setUpFaultyStrategy()); - - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - configureFaultyStrategy(_faultAmount, false); - - // We need to allow the strategy to deploy Funds more than it should - asset.mint(address(strategy), _faultAmount); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // These should all be right even though the amount deployed was actually more - checkStrategyTotals(strategy, _amount, _amount, 0, _amount); - - assertEq(asset.balanceOf(address(yieldSource)), _amount + _faultAmount); - - uint256 before = asset.balanceOf(_address); - - vm.prank(_address); - strategy.withdraw(_amount, _address, _address); - - // We should have just withdrawn '_amount' and - // not accounted for the _faultAmount but will be in the strategy now - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(asset.balanceOf(_address) - before, _amount); - assertEq(asset.balanceOf(address(strategy)), _faultAmount); - } - - function test_faultyStrategy_withdrawsToMuch( - address _address, - uint256 _amount, - uint256 _faultAmount - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _faultAmount = bound(_faultAmount, 10, MAX_BPS); - - strategy = IMockStrategy(setUpFaultyStrategy()); - - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - checkStrategyTotals(strategy, _amount, _amount, 0, _amount); - - configureFaultyStrategy(_faultAmount, false); - - // We need to allow the strategy to pull more than it should - asset.mint(address(yieldSource), _faultAmount); - - uint256 before = asset.balanceOf(_address); - - vm.prank(_address); - strategy.withdraw(_amount, _address, _address); - - // We should have just withdrawn '_amount' and - // not accounted for the _faultAmount but will be in the strategy now - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(asset.balanceOf(_address) - before, _amount); - assertEq(asset.balanceOf(address(strategy)), _faultAmount); - } - function test_deployFundsViewReentrancy( - address _address, - uint256 _amount, - uint16 _profitFactor + address _user, + uint256 _amount ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); strategy = IMockStrategy(setUpFaultyStrategy()); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - setFees(0, 0); - configureFaultyStrategy(0, true); - - // Save current values for view reentrancy checks storeCallBackVariables(_amount); - // The deposit should check against the stored variables - mintAndDepositIntoStrategy(strategy, _address, _amount); - - configureFaultyStrategy(0, false); - - createAndCheckProfit(strategy, profit, 0, 0); - - increaseTimeAndCheckBuffer(strategy, 5 days, profit / 2); - - // Check again while there is profit unlocking - configureFaultyStrategy(0, true); - - storeCallBackVariables(_amount); - - mintAndDepositIntoStrategy(strategy, _address, _amount); + mintAndDepositIntoStrategy(strategy, _user, _amount); } function test_freeFundsViewReentrancy( - address _address, - uint256 _amount, - uint16 _profitFactor + address _user, + uint256 _amount ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); strategy = IMockStrategy(setUpFaultyStrategy()); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - setFees(0, 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - increaseTimeAndCheckBuffer(strategy, 5 days, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); configureFaultyStrategy(0, true); - storeCallBackVariables(_amount / 2); - vm.prank(_address); - strategy.withdraw(_amount / 2, _address, _address); - - configureFaultyStrategy(0, false); - - createAndCheckProfit(strategy, profit, 0, 0); - - increaseTimeAndCheckBuffer(strategy, 5 days, profit / 2); - - // Check again while there is profit unlocking - configureFaultyStrategy(0, true); - - storeCallBackVariables(_amount / 2); - - vm.prank(_address); - strategy.withdraw(_amount / 2, _address, _address); - } - - function test_reportViewReentrancy( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - - strategy = IMockStrategy(setUpFaultyStrategy()); - - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - setFees(0, 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // The expected '_amount' for the callback check - uint256 assets = _amount + profit; - - configureFaultyStrategy(0, true); - - storeCallBackVariables(assets); - - createAndCheckProfit(strategy, profit, 0, 0); - - increaseTimeAndCheckBuffer(strategy, 10 days, 0); - - storeCallBackVariables(_amount); - - createAndCheckLoss(strategy, profit, 0, true); + vm.prank(_user); + strategy.withdraw(_amount / 2, _user, _user); } function test_tendViewReentrancy( - address _address, + address _user, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; strategy = IMockStrategy(setUpFaultyStrategy()); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); setFees(0, 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); + mintAndDepositIntoStrategy(strategy, _user, _amount); configureFaultyStrategy(0, true); - // Tend with some loose balance - asset.mint(address(strategy), toAirdrop); + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; storeCallBackVariables(toAirdrop); + asset.mint(address(strategy), toAirdrop); vm.prank(keeper); strategy.tend(); } function test_deployFundsReentrancy_reverts( - address _address, + address _user, uint256 _amount ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); strategy = IMockStrategy(setUpFaultyStrategy()); - vm.assume(_address != address(0) && _address != address(strategy)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) + ); setFees(0, 0); - configureFaultyStrategy(0, true); - reenter = true; + storeReentrancyVariables(_user, _amount); - // Save current values for view reentrancy checks - storeReentrancyVariables(_address, _amount); + asset.mint(_user, _amount); - asset.mint(_address, _amount); - - vm.prank(_address); + vm.prank(_user); asset.approve(address(strategy), _amount); - // The deposit should try to trigger a second deposit within it vm.expectRevert("ReentrancyGuard: reentrant call"); - vm.prank(_address); - strategy.deposit(_amount, _address); + vm.prank(_user); + strategy.deposit(_amount, _user); checkStrategyTotals(strategy, 0, 0, 0, 0); vm.expectRevert("ReentrancyGuard: reentrant call"); - vm.prank(_address); - strategy.mint(_amount, _address); + vm.prank(_user); + strategy.mint(_amount, _user); checkStrategyTotals(strategy, 0, 0, 0, 0); } function test_freeFundsReentrancy_reverts( - address _address, + address _user, uint256 _amount ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); @@ -302,82 +136,33 @@ contract FaultyStrategy is Setup { strategy = IMockStrategy(setUpFaultyStrategy()); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); setFees(0, 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - increaseTimeAndCheckBuffer(strategy, 5 days, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); configureFaultyStrategy(0, true); reenter = true; - - // Save current values for reentrancy - storeReentrancyVariables(_address, _amount); + storeReentrancyVariables(_user, _amount); vm.expectRevert("ReentrancyGuard: reentrant call"); - vm.prank(_address); - strategy.withdraw(_amount, _address, _address); + vm.prank(_user); + strategy.withdraw(_amount, _user, _user); checkStrategyTotals(strategy, _amount, _amount, 0, _amount); vm.expectRevert("ReentrancyGuard: reentrant call"); - vm.prank(_address); - strategy.redeem(_amount, _address, _address); + vm.prank(_user); + strategy.redeem(_amount, _user, _user); checkStrategyTotals(strategy, _amount, _amount, 0, _amount); } - // Reentrancy cant be allowed during a report call. - function test_reportReentrancy_reverts( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - - strategy = IMockStrategy(setUpFaultyStrategy()); - - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) - ); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - setFees(0, 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - configureFaultyStrategy(0, true); - - storeReentrancyVariables(_address, _amount); - - reenter = true; - - asset.mint(address(strategy), profit); - - vm.expectRevert("ReentrancyGuard: reentrant call"); - vm.prank(keeper); - strategy.report(); - - checkStrategyTotals( - strategy, - _amount, - _amount - profit, - profit, - _amount - ); - } - function test_tendReentrancy_reverts( - address _address, + address _user, uint256 _amount ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); @@ -385,36 +170,29 @@ contract FaultyStrategy is Setup { strategy = IMockStrategy(setUpFaultyStrategy()); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); setFees(0, 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); + mintAndDepositIntoStrategy(strategy, _user, _amount); configureFaultyStrategy(0, true); - reenter = true; - - storeReentrancyVariables(_address, _amount); + storeReentrancyVariables(_user, _amount); vm.expectRevert("ReentrancyGuard: reentrant call"); vm.prank(keeper); strategy.tend(); } - // This function simulates being called during a external call of a deposit withdraw or report. - // This should return the same values as will be stored right before the call and checked right after the call. function callBack( uint256 _pps, uint256 _convertAmountToShares, uint256 _convertAmountToAssets ) public { - // If 'reenter' we will actually try to deposit if not just check values for views if (reenter) { - // Try and deposit back into the strategy within the original call mintAndDepositIntoStrategy(strategy, addr, amount); } else { assertEq(_pps, pps); @@ -429,11 +207,8 @@ contract FaultyStrategy is Setup { convertAmountToAssets = strategy.convertToAssets(_amount); } - function storeReentrancyVariables( - address _address, - uint256 _amount - ) public { - addr = _address; + function storeReentrancyVariables(address _user, uint256 _amount) public { + addr = _user; amount = _amount; } } diff --git a/src/test/InvariantsSingleStrategy.t.sol b/src/test/InvariantsSingleStrategy.t.sol index 1554cb4..797e058 100644 --- a/src/test/InvariantsSingleStrategy.t.sol +++ b/src/test/InvariantsSingleStrategy.t.sol @@ -51,14 +51,6 @@ contract SingleStrategyInvariantTest is BaseInvariant { assert_maxRedeemEqualsMaxWithdraw(); } - function invariant_unlockingTime() public { - assert_unlockingTime(); - } - - function invariant_unlockedShares() public { - assert_unlockedShares(); - } - function invariant_previewMintAndConvertToAssets() public { assert_previewMintAndConvertToAssets(); } diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index 197633d..5be9db7 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -1,7 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.18; -import "forge-std/console.sol"; import {Setup} from "./utils/Setup.sol"; contract ProfitLockingTest is Setup { @@ -9,2053 +8,171 @@ contract ProfitLockingTest is Setup { super.setUp(); } - function test_gain_NoFeesNoBuffer( - address _address, - uint128 amount, - uint16 _profitFactor - ) public { - uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - profit / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + (profit / 2) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gainProtocolFee_NoPerformanceFeeNoBuffer( - address _address, + function test_reportRealizesProtocolAndPerformanceFees( + address _user, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set protocol fee to 100 bps so there will always be fees charged over a 10 day period with minFuzzAmount - uint16 protocolFee = 1_000; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit + _user != address(0) && + _user != address(strategy) && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) ); - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + totalExpectedFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees - ); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees - ); - - if (totalExpectedFees > 0) { - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - vm.prank(protocolFeeRecipient); - strategy.redeem( - totalExpectedFees, - protocolFeeRecipient, - protocolFeeRecipient - ); - } - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gainPerformanceFee_NoProtocolNoBuffer( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set perf fee to 10% - uint16 protocolFee = 0; + uint16 protocolFee = 1_000; uint16 performanceFee = 1_000; setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 totalFeeAssets = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFees = (totalFeeAssets * protocolFee) / MAX_BPS; + uint256 expectedPerformanceFees = totalFeeAssets - expectedProtocolFees; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); + asset.mint(address(strategy), profit); - assertEq(strategy.pricePerShare(), wad, "!pps"); + uint256 ppsBefore = strategy.pricePerShare(); - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, profit, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertGt(strategy.pricePerShare(), ppsBefore, "!pps"); assertApproxEq( strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, + expectedProtocolFees, 100 ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + totalExpectedFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees - ); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees - ); - - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - vm.prank(performanceFeeRecipient); - strategy.redeem( - totalExpectedFees, - performanceFeeRecipient, - performanceFeeRecipient - ); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gainProtocolFeePerformanceFee_NoBuffer( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set perf fee to 10% protocol fee to 100 bps - uint16 protocolFee = 1_000; - uint16 performanceFee = 1_000; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - // Adjust what the performance fee expects to get when there is a protocol fee. - expectedPerformanceFee = expectedPerformanceFee - expectedProtocolFee; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - assertApproxEq( strategy.convertToAssets( strategy.balanceOf(performanceFeeRecipient) ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, + expectedPerformanceFees, 100 ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + totalExpectedFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees - ); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees - ); - - if (expectedPerformanceFee > 0) { - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - vm.prank(performanceFeeRecipient); - strategy.redeem( - expectedPerformanceFee, - performanceFeeRecipient, - performanceFeeRecipient - ); - } - - expectedAssetsForFees = strategy.convertToAssets(expectedProtocolFee); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - expectedProtocolFee - ); - - if (expectedProtocolFee > 0) { - vm.prank(protocolFeeRecipient); - strategy.redeem( - expectedProtocolFee, - protocolFeeRecipient, - protocolFeeRecipient - ); - } - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); } - function test_gainBuffer_noProtocolFeeNoPerformanceFee( - address _address, + function test_reportDoesNotDoubleCharge( + address _user, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); - // set fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + setFees(0, 1_000); + mintAndDepositIntoStrategy(strategy, _user, _amount); uint256 profit = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), profit); - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - uint256 newAmount = _amount + profit; - - uint256 secondExpectedSharesForFees = strategy.convertToShares( - expectedProtocolFee + expectedPerformanceFee - ); - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); + vm.prank(keeper); + strategy.report(); - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - - ((profit - totalExpectedFees) / 2) + - strategy.convertToShares(profit) - ); + uint256 feeShares = strategy.balanceOf(performanceFeeRecipient); - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - profit + totalExpectedFees + secondExpectedSharesForFees + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq( + strategy.balanceOf(performanceFeeRecipient), + feeShares, + "!fee" ); - - vm.prank(_address); - strategy.redeem(newAmount - profit, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); } - function test_gainProtocolFeeBuffer_noPerformanceFee( - address _address, + function test_feeSyncOnDepositMatchesLivePrice( + address _user, + address _depositor, uint256 _amount, uint16 _profitFactor ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) + _user != address(0) && + _depositor != address(0) && + _user != _depositor && + _user != address(strategy) && + _depositor != address(strategy) && + _user != address(yieldSource) && + _depositor != address(yieldSource) ); - // set fees - uint16 protocolFee = 1_000; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + setFees(0, 1_000); + mintAndDepositIntoStrategy(strategy, _user, _amount); uint256 profit = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), profit); - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - uint256 newAmount = _amount + profit; - - uint256 secondExpectedSharesForFees = strategy.convertToShares( - expectedProtocolFee + expectedPerformanceFee - ); - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - - ((profit - totalExpectedFees) / 2) + - strategy.convertToShares(profit) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - profit + totalExpectedFees + secondExpectedSharesForFees - ); - - assertGt(strategy.pricePerShare(), wad, "pps decreased"); + skip(1); - vm.prank(_address); - strategy.redeem(newAmount - profit, _address, _address); + uint256 ppsBefore = strategy.pricePerShare(); + uint256 preview = strategy.previewDeposit(_amount); - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees + secondExpectedSharesForFees - ); + asset.mint(_depositor, _amount); + vm.prank(_depositor); + asset.approve(address(strategy), _amount); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees + secondExpectedSharesForFees - ); + vm.prank(_depositor); + uint256 minted = strategy.deposit(_amount, _depositor); - uint256 balance = strategy.balanceOf(protocolFeeRecipient); - if (balance > 0) { - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - vm.prank(protocolFeeRecipient); - strategy.redeem( - balance, - protocolFeeRecipient, - protocolFeeRecipient - ); - } + assertGe(strategy.pricePerShare(), ppsBefore, "!pps"); + assertEq(minted, preview, "!preview"); - checkStrategyTotals(strategy, 0, 0, 0, 0); + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); - assertEq(strategy.pricePerShare(), wad, "pps reset"); + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); } - function test_gainPerformanceFeeBuffer_noProtocolFee( - address _address, + function test_settingProfitUnlockTimeDoesNotCreateABuffer( + address _user, uint256 _amount, - uint16 _profitFactor + uint16 _profitFactor, + uint32 _unlockTime ) public { _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + uint256 unlockTime = bound(uint256(_unlockTime), 0, 31_556_952); vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set fees - uint16 protocolFee = 0; - uint16 performanceFee = 1_000; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - uint256 newAmount = _amount + profit; - - uint256 secondExpectedSharesForFees = (strategy.convertToShares( - profit - ) * performanceFee) / MAX_BPS; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) ); - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - - ((profit - totalExpectedFees) / 2) + - strategy.convertToShares(profit) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - profit + totalExpectedFees + secondExpectedSharesForFees - ); - - vm.prank(_address); - strategy.redeem(newAmount - profit, _address, _address); - - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees + secondExpectedSharesForFees - ); - - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees + secondExpectedSharesForFees - ); + setFees(0, 0); - assertGt(strategy.pricePerShare(), wad, "pps decreased"); + vm.prank(management); + strategy.setProfitMaxUnlockTime(unlockTime); - uint256 balance = strategy.balanceOf(performanceFeeRecipient); - vm.prank(performanceFeeRecipient); - strategy.redeem( - balance, - performanceFeeRecipient, - performanceFeeRecipient - ); + mintAndDepositIntoStrategy(strategy, _user, _amount); - checkStrategyTotals(strategy, 0, 0, 0, 0); + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 ppsBefore = strategy.pricePerShare(); + asset.mint(address(strategy), profit); - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } + assertEq(strategy.pricePerShare(), ppsBefore, "!pps frozen"); - function test_gainProtocolFeePerformanceFeeBuffer( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set fees - uint16 protocolFee = 1_000; - uint16 performanceFee = 1_000; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - // Adjust what the performance fee expects to get when there is a protocol fee. - expectedPerformanceFee = expectedPerformanceFee - expectedProtocolFee; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - uint256 newAmount = _amount + profit; - - uint256 secondExpectedSharesForFees = (strategy.convertToShares( - profit - ) * performanceFee) / MAX_BPS; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - - ((profit - totalExpectedFees) / 2) + - strategy.convertToShares(profit) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - newAmount - profit + totalExpectedFees + secondExpectedSharesForFees - ); - - vm.prank(_address); - // Use newAmount - profit here to avoid stack to deep - strategy.redeem(newAmount - profit, _address, _address); - - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees + secondExpectedSharesForFees - ); - - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees + secondExpectedSharesForFees - ); - - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - uint256 balance = strategy.balanceOf(protocolFeeRecipient); - if (balance > 0) { - vm.prank(protocolFeeRecipient); - strategy.redeem( - balance, - protocolFeeRecipient, - protocolFeeRecipient - ); - } - - balance = strategy.balanceOf(performanceFeeRecipient); - vm.prank(performanceFeeRecipient); - strategy.redeem( - balance, - performanceFeeRecipient, - performanceFeeRecipient - ); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_loss_NoFeesNoBuffer( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 1, 5_000)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 loss = (_amount * _lossFactor) / MAX_BPS; - uint256 expectedProtocolFee = 0; - - createAndCheckLoss(strategy, loss, expectedProtocolFee, true); - - assertRelApproxEq( - strategy.pricePerShare(), - wad - ((wad * _lossFactor) / MAX_BPS), - MAX_BPS / 10 - ); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad - ((wad * _lossFactor) / MAX_BPS), - MAX_BPS / 10 - ); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_lossProtocolFees_NoBuffer( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 1, 5_000)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 1_000; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 loss = (_amount * _lossFactor) / MAX_BPS; - uint256 expectedProtocolFee = 0; - - uint256 totalExpectedFees = expectedProtocolFee; - createAndCheckLoss( - strategy, - loss, - expectedProtocolFee, - false // Don't check protocol fees with overall loss - ); - - assertRelApproxEq( - strategy.pricePerShare(), - wad - ((wad * _lossFactor) / MAX_BPS), - MAX_BPS / 10 - ); - - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount + totalExpectedFees - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount + totalExpectedFees - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad - ((wad * _lossFactor) / MAX_BPS), - MAX_BPS / 10 - ); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount + totalExpectedFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 balance = strategy.balanceOf(protocolFeeRecipient); - if (balance > 0) { - vm.prank(protocolFeeRecipient); - strategy.redeem( - balance, - protocolFeeRecipient, - protocolFeeRecipient - ); - } - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_lossBuffer_NoProtocolFees( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, 5_000)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - //uint16 performanceFee = 0; - setFees(protocolFee, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 loss = (_amount * _lossFactor) / MAX_BPS; - uint256 expectedProtocolFee = 0; - uint256 expectedPerformanceFee = (loss * 0) / MAX_BPS; - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - - // Simulate an original profit of 2x the loss - createAndCheckProfit( - strategy, - loss * 2, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - checkStrategyTotals( - strategy, - _amount + loss * 2, - _amount + loss * 2, - 0, - _amount + loss * 2 - ); - - // Half way through we should have the full loss still as a buffer - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, loss); - - checkStrategyTotals( - strategy, - _amount + loss * 2, - _amount + loss * 2, - 0, - _amount + loss * 2 + totalExpectedFees - loss - ); - - uint256 newAmount = _amount + loss * 2; - - uint256 secondExpectedSharesForFees = strategy.convertToShares( - expectedProtocolFee + expectedPerformanceFee - ); - - // We will not burn the difference between the remaining buffer and shares it will take post profit to cover it - uint256 toNotBurn = loss - strategy.convertToShares(loss); - createAndCheckLoss(strategy, loss, expectedProtocolFee, true); - - // We should have burned the full buffer - assertApproxEq( - strategy.balanceOf(address(strategy)), - toNotBurn, - 1, - "!strategy bal" - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - checkStrategyTotals( - strategy, - newAmount - loss, - newAmount - loss, - 0, - newAmount - - loss * - 2 + - totalExpectedFees + - secondExpectedSharesForFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_lossProtocolFeesBuffer( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 10, 5_000)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 1_000; - setFees(protocolFee, 0); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 loss = (_amount * _lossFactor) / MAX_BPS; - uint256 expectedProtocolFee = 0; - uint256 expectedPerformanceFee = (loss * 0) / MAX_BPS; - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - - // Simulate an original profit of 2x the loss - createAndCheckProfit( - strategy, - loss * 2, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount + loss * 2, - _amount + loss * 2, - 0, - _amount + loss * 2 - ); - - // Half way through we should have the full loss still as a buffer - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (loss * 2 - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + loss * 2, - _amount + loss * 2, - 0, - _amount + loss * 2 - ((loss * 2 - totalExpectedFees) / 2) - ); - - uint256 newAmount = _amount + loss * 2; - - uint256 secondExpectedSharesForFees = strategy.convertToShares( - expectedProtocolFee + expectedPerformanceFee - ); - - createAndCheckLoss( - strategy, - loss, - expectedProtocolFee, - false // Don't check protocol fees with overall loss - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - console.log("Current bal ", strategy.balanceOf(address(strategy))); - checkStrategyTotals( - strategy, - newAmount - loss, - newAmount - loss, - 0, - newAmount - - loss * - 2 + - totalExpectedFees + - secondExpectedSharesForFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 balance = strategy.balanceOf(protocolFeeRecipient); - if (balance > 0) { - vm.prank(protocolFeeRecipient); - strategy.redeem( - balance, - protocolFeeRecipient, - protocolFeeRecipient - ); - } - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_NoGainFeesOrBuffer( - address _address, - uint128 amount, - uint16 _profitFactor - ) public { - uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); - _profitFactor = 0; - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - assertApproxEq( - strategy.convertToAssets( - strategy.balanceOf(performanceFeeRecipient) - ), - expectedPerformanceFee, - 100 - ); - assertApproxEq( - strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), - expectedProtocolFee, - 100 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - profit / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + (profit / 2) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gain_NoFeesNoBuffer_noLocking( - address _address, - uint128 amount, - uint16 _profitFactor - ) public { - uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - - // Set max unlocking time to 0. - vm.prank(management); - strategy.setProfitMaxUnlockTime(0); - assertEq(strategy.profitMaxUnlockTime(), 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - // All profit should have been unlocked instantly. - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - assertGt(strategy.pricePerShare(), wad, "!pps"); - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - // Nothing should change - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gain_NoFeesNoBuffer_noLocking_withdrawAll( - address _address, - uint128 amount, - uint16 _profitFactor - ) public { - uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - - // Set max unlocking time to 0. - vm.prank(management); - strategy.setProfitMaxUnlockTime(0); - assertEq(strategy.profitMaxUnlockTime(), 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - // All profit should have been unlocked instantly. - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - assertGt(strategy.pricePerShare(), wad, "!pps"); - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - // Should be able to withdraw all right away - uint256 beforeBalance = asset.balanceOf(_address); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - assertEq(asset.balanceOf(_address), beforeBalance + _amount + profit); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gainFees_NoBuffer_noLocking( - address _address, - uint128 amount, - uint16 _profitFactor - ) public { - uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 1_000; - uint16 performanceFee = 1_000; - setFees(protocolFee, performanceFee); - - // Set max unlocking time to 0. - vm.prank(management); - strategy.setProfitMaxUnlockTime(0); - assertEq(strategy.profitMaxUnlockTime(), 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - expectedPerformanceFee -= expectedProtocolFee; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - - asset.mint(address(strategy), profit); - - vm.prank(keeper); - (uint256 _profit, ) = strategy.report(); - - assertEq(profit, _profit, "profit reported wrong"); - - // All profit should have been unlocked instantly. - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - assertGt(strategy.pricePerShare(), wad, "!pps"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + totalExpectedFees - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - uint256 expectedAssetsForFees = strategy.convertToAssets( - totalExpectedFees - ); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - totalExpectedFees - ); - - if (expectedPerformanceFee > 0) { - assertGt(strategy.pricePerShare(), wad, "pps decreased"); - - vm.prank(performanceFeeRecipient); - strategy.redeem( - expectedPerformanceFee, - performanceFeeRecipient, - performanceFeeRecipient - ); - } - - expectedAssetsForFees = strategy.convertToAssets(expectedProtocolFee); - checkStrategyTotals( - strategy, - expectedAssetsForFees, - expectedAssetsForFees, - 0, - expectedProtocolFee - ); - - if (expectedProtocolFee > 0) { - vm.prank(protocolFeeRecipient); - strategy.redeem( - expectedProtocolFee, - protocolFeeRecipient, - protocolFeeRecipient - ); - } - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_gainBuffer_noFees_noLocking_resets( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - // Make sure we have active unlocking - assertGt(strategy.profitUnlockingRate(), 0); - assertGt(strategy.fullProfitUnlockDate(), 0); - assertGt(strategy.balanceOf(address(strategy)), 0); - - // Set max unlocking time to 0. - vm.prank(management); - strategy.setProfitMaxUnlockTime(0); - // Make sure it reset all unlocking rates. - assertEq(strategy.profitMaxUnlockTime(), 0); - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - assertEq(strategy.balanceOf(address(strategy)), 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - uint256 newAmount = _amount + profit; - - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - // Should unlock everything right away. - checkStrategyTotals( - strategy, - newAmount + profit, - newAmount + profit, - 0, - _amount - ); - - increaseTimeAndCheckBuffer(strategy, 0, 0); - - vm.prank(_address); - strategy.redeem(newAmount - profit, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_buffer_noGainReport( - address _address, - uint256 _amount, - uint16 _profitFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 profit = (_amount * _profitFactor) / MAX_BPS; - - uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; - uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / - MAX_BPS; - - uint256 totalExpectedFees = expectedPerformanceFee + - expectedProtocolFee; - createAndCheckProfit( - strategy, - profit, - expectedProtocolFee, - expectedPerformanceFee - ); - - assertEq(strategy.pricePerShare(), wad, "!pps"); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ); - - increaseTimeAndCheckBuffer( - strategy, - profitMaxUnlockTime / 2, - (profit - totalExpectedFees) / 2 - ); - - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - // Make sure we have active unlocking - assertGt(strategy.profitUnlockingRate(), 0); - assertGt(strategy.fullProfitUnlockDate(), 0); - assertGt(strategy.balanceOf(address(strategy)), 0); - uint256 pps = strategy.pricePerShare(); - - // Report with no profit or loss - vm.prank(keeper); - strategy.report(); - - // Should be the same as before - assertEq(strategy.pricePerShare(), pps, "pps"); - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount + profit - ((profit - totalExpectedFees) / 2) - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - // Everything should be unlocked now. - assertRelApproxEq( - strategy.pricePerShare(), - wad + ((wad * _profitFactor) / MAX_BPS), - MAX_BPS - ); - checkStrategyTotals( - strategy, - _amount + profit, - _amount + profit, - 0, - _amount - ); - - vm.prank(_address); - strategy.redeem(_amount, _address, _address); - - checkStrategyTotals(strategy, 0, 0, 0, 0); - - assertEq(strategy.pricePerShare(), wad, "pps reset"); - } - - function test_loss_NoFeesNoBuffer_noUnlock( - address _address, - uint256 _amount, - uint16 _lossFactor - ) public { - _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); - _lossFactor = uint16(bound(uint256(_lossFactor), 1, 5_000)); - vm.assume( - _address != address(0) && - _address != address(strategy) && - _address != protocolFeeRecipient && - _address != performanceFeeRecipient && - _address != address(yieldSource) - ); - // set all fees to 0 - uint16 protocolFee = 0; - uint16 performanceFee = 0; - setFees(protocolFee, performanceFee); - - // Set max unlocking time to 0. - vm.prank(management); - strategy.setProfitMaxUnlockTime(0); - assertEq(strategy.profitMaxUnlockTime(), 0); - - mintAndDepositIntoStrategy(strategy, _address, _amount); - // Increase time to simulate interest being earned - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); - - uint256 loss = (_amount * _lossFactor) / MAX_BPS; - uint256 expectedProtocolFee = 0; - - createAndCheckLoss(strategy, loss, expectedProtocolFee, true); - - assertEq(strategy.profitUnlockingRate(), 0, "!rate"); - assertEq(strategy.fullProfitUnlockDate(), 0, "date"); - assertRelApproxEq( - strategy.pricePerShare(), - wad - ((wad * _lossFactor) / MAX_BPS), - MAX_BPS / 10 - ); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount - ); - - increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); - - assertRelApproxEq( - strategy.pricePerShare(), - wad - ((wad * _lossFactor) / MAX_BPS), - MAX_BPS / 10 - ); - - checkStrategyTotals( - strategy, - _amount - loss, - _amount - loss, - 0, - _amount - ); + skip(1); - vm.prank(_address); - strategy.redeem(_amount, _address, _address); + assertGt(strategy.pricePerShare(), ppsBefore, "!pps"); - checkStrategyTotals(strategy, 0, 0, 0, 0); + skip(profitMaxUnlockTime); - assertEq(strategy.pricePerShare(), wad, "pps reset"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); } } diff --git a/src/test/Shutdown.t.sol b/src/test/Shutdown.t.sol index 1997533..9ad80ea 100644 --- a/src/test/Shutdown.t.sol +++ b/src/test/Shutdown.t.sol @@ -252,7 +252,7 @@ contract ShutdownTest is Setup { // Make sure it recorded the correct amount checkStrategyTotals(strategy, _amount, 0, _amount, _amount); - // PPS should not change. + // PPS stays frozen until report() breaks the latch. assertEq(strategy.pricePerShare(), pps); assertEq(asset.balanceOf(address(strategy)), _amount + profit); @@ -263,8 +263,6 @@ contract ShutdownTest is Setup { vm.prank(management); strategy.report(); - skip(strategy.profitMaxUnlockTime()); - vm.prank(_address); strategy.redeem(_amount, _address, _address); @@ -308,10 +306,10 @@ contract ShutdownTest is Setup { strategy.emergencyWithdraw(_amount - loss); // Make sure it recorded the correct amount. - // Loss will still be counted as debt. + // Loss stays counted as debt until report() forces a sync. checkStrategyTotals(strategy, _amount, loss, _amount - loss, _amount); - // PPS should not change. + // PPS stays frozen until report() breaks the latch. assertEq(strategy.pricePerShare(), pps); assertEq(asset.balanceOf(address(strategy)), _amount - loss); diff --git a/src/test/e2e.t.sol b/src/test/e2e.t.sol index 67157d6..7546224 100644 --- a/src/test/e2e.t.sol +++ b/src/test/e2e.t.sol @@ -355,7 +355,7 @@ contract e2eTest is Setup { vm.prank(_secondAddress); info.strat.redeem(balance, _secondAddress, _secondAddress); - assertGt(asset.balanceOf(_secondAddress) - before, info.toDeposit); + assertLe(asset.balanceOf(_secondAddress) - before, info.toDeposit); assertEq(info.strat.pricePerShare(), wad); checkStrategyTotals(info.strat, 0, 0, 0); diff --git a/src/test/mocks/MockFaultyStrategy.sol b/src/test/mocks/MockFaultyStrategy.sol index d43c857..412c9da 100644 --- a/src/test/mocks/MockFaultyStrategy.sol +++ b/src/test/mocks/MockFaultyStrategy.sol @@ -40,14 +40,21 @@ contract MockFaultyStrategy is BaseStrategy { MockYieldSource(yieldSource).withdraw(_amount + fault); } + function _totalAssets() internal view override returns (uint256) { + return + MockYieldSource(yieldSource).balance() + + ERC20(asset).balanceOf(address(this)); + } + function _harvestAndReport() internal override returns (uint256) { uint256 balance = ERC20(asset).balanceOf(address(this)); if (balance > 0) { MockYieldSource(yieldSource).deposit(balance); } - uint256 total = MockYieldSource(yieldSource).balance(); - if (doCallBack) callBack(total); - return total; + // Write paths now sync through harvest before user actions. Keep this + // mock focused on deploy/free/tend callbacks so the reentrancy tests + // still isolate the path they are named after. + return _totalAssets(); } function _tend(uint256 _idle) internal override { diff --git a/src/test/mocks/MockIlliquidStrategy.sol b/src/test/mocks/MockIlliquidStrategy.sol index 9e37ad5..fc10195 100644 --- a/src/test/mocks/MockIlliquidStrategy.sol +++ b/src/test/mocks/MockIlliquidStrategy.sol @@ -25,16 +25,18 @@ contract MockIlliquidStrategy is BaseStrategy { //MockYieldSource(yieldSource).withdraw(_amount); } - function _harvestAndReport() internal override returns (uint256) { - uint256 balance = ERC20(asset).balanceOf(address(this)); - if (balance > 0) { - MockYieldSource(yieldSource).deposit(balance / 2); - } + function _totalAssets() internal view override returns (uint256) { return MockYieldSource(yieldSource).balance() + ERC20(asset).balanceOf(address(this)); } + function _harvestAndReport() internal view override returns (uint256) { + // Live write-path syncing now runs before user withdraw/redeem flows. + // Keep this mock's withdrawal limit stable by not moving idle funds here. + return _totalAssets(); + } + function _tend(uint256 /*_idle*/) internal override { uint256 balance = MockYieldSource(yieldSource).balance(); if (balance > 0) { diff --git a/src/test/mocks/MockStorage.sol b/src/test/mocks/MockStorage.sol index 2b6fcf1..2f35c6b 100644 --- a/src/test/mocks/MockStorage.sol +++ b/src/test/mocks/MockStorage.sol @@ -22,21 +22,16 @@ contract MockStorage { mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. - // Assets data to track total the strategy holds. - // We manually track `totalAssets` to prevent PPS manipulation through airdrops. - uint256 totalAssets; - - - // Variables for profit reporting and locking. + // Assets data to track the last realized total the strategy held. + uint256 lastTotalAssets; + // Variables for profit reporting. // We use uint96 for time stamps to fit in the same slot as an address. // We will surely all be dead by the time the slot overflows. - uint256 profitUnlockingRate; // The rate at which locked profit is unlocking. - uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock. address keeper; // Address given permission to call {report} and {tend}. uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over. uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. address performanceFeeRecipient; // The address to pay the `performanceFee` to. - uint96 lastReport; // The last time a {report} was called. + uint96 lastReport; // The last time accounting synced. // Access management variables. diff --git a/src/test/mocks/MockStrategy.sol b/src/test/mocks/MockStrategy.sol index 74b5f8b..1eb7bde 100644 --- a/src/test/mocks/MockStrategy.sol +++ b/src/test/mocks/MockStrategy.sol @@ -32,14 +32,18 @@ contract MockStrategy is BaseStrategy { MockYieldSource(yieldSource).withdraw(_amount); } + function _totalAssets() internal view override returns (uint256) { + return + MockYieldSource(yieldSource).balance() + + ERC20(asset).balanceOf(address(this)); + } + function _harvestAndReport() internal override returns (uint256) { uint256 balance = ERC20(asset).balanceOf(address(this)); if (balance > 0 && !TokenizedStrategy.isShutdown()) { MockYieldSource(yieldSource).deposit(balance); } - return - MockYieldSource(yieldSource).balance() + - ERC20(asset).balanceOf(address(this)); + return _totalAssets(); } function _tend(uint256 /*_idle*/) internal override { diff --git a/src/test/utils/BaseInvariant.sol b/src/test/utils/BaseInvariant.sol index f19fd4b..ec3c7c1 100644 --- a/src/test/utils/BaseInvariant.sol +++ b/src/test/utils/BaseInvariant.sol @@ -2,23 +2,21 @@ pragma solidity >=0.8.18; import "forge-std/console.sol"; -import {Setup, TokenizedStrategy} from "./Setup.sol"; +import {Setup} from "./Setup.sol"; abstract contract BaseInvariant is Setup { function setUp() public virtual override { super.setUp(); } - function assert_totalAssets( - uint256 _totalDeposits, - uint256 _totalWithdraw, - uint256 _totalGain, - uint256 _totalLosses - ) public { - assertEq( - strategy.totalAssets(), - _totalDeposits + _totalGain - _totalWithdraw - _totalLosses - ); + function assert_totalAssets(uint256, uint256, uint256, uint256) public { + uint256 totalAssets_ = strategy.totalAssets(); + uint256 actualAssets = yieldSource.balance() + + asset.balanceOf(address(strategy)); + + if (totalAssets_ != actualAssets) { + assertEq(totalAssets_, strategy.lastTotalAssets()); + } } function assert_maxWithdraw() public { @@ -41,53 +39,15 @@ abstract contract BaseInvariant is Setup { assertApproxEq( strategy.maxWithdraw(msg.sender), strategy.convertToAssets(strategy.maxRedeem(msg.sender)), - 3 + 10 ); assertApproxEq( strategy.maxRedeem(msg.sender), strategy.convertToShares(strategy.maxWithdraw(msg.sender)), - 3 + 10 ); } - function assert_unlockingTime() public { - uint256 unlockingDate = strategy.fullProfitUnlockDate(); - uint256 balance = strategy.balanceOf(address(strategy)); - uint256 unlockedShares = strategy.unlockedShares(); - if (unlockingDate != 0 && strategy.profitUnlockingRate() > 0) { - if (block.timestamp == strategy.lastReport()) { - assertEq(unlockedShares, 0); - assertGt(balance, 0); - } else if (block.timestamp < unlockingDate) { - assertGt(unlockedShares, 0); - assertGt(balance, 0); - } else { - // We should have unlocked full balance - assertEq(balance, 0); - assertGt(unlockedShares, 0); - } - } else { - assertEq(balance, 0); - } - } - - function assert_unlockedShares() public { - uint256 unlockedShares = strategy.unlockedShares(); - uint256 fullBalance = strategy.balanceOf(address(strategy)) + - unlockedShares; - uint256 unlockingDate = strategy.fullProfitUnlockDate(); - if ( - unlockingDate != 0 && - strategy.profitUnlockingRate() > 0 && - block.timestamp < unlockingDate - ) { - assertLt(unlockedShares, fullBalance); - } else { - assertEq(unlockedShares, fullBalance); - assertEq(strategy.balanceOf(address(strategy)), 0); - } - } - function assert_previewMintAndConvertToAssets() public { assertApproxEq( strategy.previewMint(wad), diff --git a/src/test/utils/Setup.sol b/src/test/utils/Setup.sol index 728c9ea..b99e787 100644 --- a/src/test/utils/Setup.sol +++ b/src/test/utils/Setup.sol @@ -215,7 +215,6 @@ contract Setup is ExtendedTest, IEvents { "total assets wrong" ); assertEq(_strategy.lastReport(), block.timestamp, "last report"); - assertEq(_strategy.unlockedShares(), 0, "unlocked Shares"); } function createAndCheckLoss( diff --git a/yarn.lock b/yarn.lock index 79d407d..e80cbe0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4,19 +4,19 @@ "@babel/code-frame@^7.0.0": version "7.18.6" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.18.6.tgz#3b25d38c89600baa2dcc219edfa88a74eb2c427a" + resolved "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz" integrity sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q== dependencies: "@babel/highlight" "^7.18.6" "@babel/helper-validator-identifier@^7.18.6": version "7.19.1" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz#7eea834cf32901ffdc1a7ee555e2f9c27e249ca2" + resolved "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz" integrity sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w== "@babel/highlight@^7.18.6": version "7.18.6" - resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.18.6.tgz#81158601e93e2563795adcbfbdf5d64be3f2ecdf" + resolved "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz" integrity sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g== dependencies: "@babel/helper-validator-identifier" "^7.18.6" @@ -25,26 +25,26 @@ "@solidity-parser/parser@^0.15.0": version "0.15.0" - resolved "https://registry.yarnpkg.com/@solidity-parser/parser/-/parser-0.15.0.tgz#1d359be40be84f174dd616ccfadcf43346c6bf63" + resolved "https://registry.npmjs.org/@solidity-parser/parser/-/parser-0.15.0.tgz" integrity sha512-5UFJJTzWi1hgFk6aGCZ5rxG2DJkCJOzJ74qg7UkWSNCDSigW+CJLoYUb5bLiKrtI34Nr9rpFSUNHfkqtlL+N/w== dependencies: antlr4ts "^0.5.0-alpha.4" "@solidity-parser/parser@^0.16.0": version "0.16.0" - resolved "https://registry.yarnpkg.com/@solidity-parser/parser/-/parser-0.16.0.tgz#1fb418c816ca1fc3a1e94b08bcfe623ec4e1add4" + resolved "https://registry.npmjs.org/@solidity-parser/parser/-/parser-0.16.0.tgz" integrity sha512-ESipEcHyRHg4Np4SqBCfcXwyxxna1DgFVz69bgpLV8vzl/NP1DtcKsJ4dJZXWQhY/Z4J2LeKBiOkOVZn9ct33Q== dependencies: antlr4ts "^0.5.0-alpha.4" "@types/minimatch@^3.0.3": version "3.0.5" - resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.5.tgz#1001cc5e6a3704b83c236027e77f2f58ea010f40" + resolved "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.5.tgz" integrity sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ== ajv@^6.12.6: version "6.12.6" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" + resolved "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== dependencies: fast-deep-equal "^3.1.1" @@ -54,7 +54,7 @@ ajv@^6.12.6: ajv@^8.0.1: version "8.12.0" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.12.0.tgz#d1a0527323e22f53562c567c00991577dfbe19d1" + resolved "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz" integrity sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA== dependencies: fast-deep-equal "^3.1.1" @@ -64,71 +64,71 @@ ajv@^8.0.1: ansi-regex@^5.0.1: version "5.0.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" + resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== ansi-styles@^3.2.1: version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" + resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.3.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" + resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz" integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== dependencies: color-convert "^2.0.1" antlr4@^4.11.0: version "4.12.0" - resolved "https://registry.yarnpkg.com/antlr4/-/antlr4-4.12.0.tgz#e2323fbb057c77068a174914b0533398aeaba56a" + resolved "https://registry.npmjs.org/antlr4/-/antlr4-4.12.0.tgz" integrity sha512-23iB5IzXJZRZeK9TigzUyrNc9pSmNqAerJRBcNq1ETrmttMWRgaYZzC561IgEO3ygKsDJTYDTozABXa4b/fTQQ== antlr4ts@^0.5.0-alpha.4: version "0.5.0-alpha.4" - resolved "https://registry.yarnpkg.com/antlr4ts/-/antlr4ts-0.5.0-alpha.4.tgz#71702865a87478ed0b40c0709f422cf14d51652a" + resolved "https://registry.npmjs.org/antlr4ts/-/antlr4ts-0.5.0-alpha.4.tgz" integrity sha512-WPQDt1B74OfPv/IMS2ekXAKkTZIHl88uMetg6q3OTqgFxZ/dxDXI0EWLyZid/1Pe6hTftyg5N7gel5wNAGxXyQ== argparse@^2.0.1: version "2.0.1" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" + resolved "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== array-differ@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/array-differ/-/array-differ-3.0.0.tgz#3cbb3d0f316810eafcc47624734237d6aee4ae6b" + resolved "https://registry.npmjs.org/array-differ/-/array-differ-3.0.0.tgz" integrity sha512-THtfYS6KtME/yIAhKjZ2ul7XI96lQGHRputJQHO80LAWQnuGP4iCIN8vdMRboGbIEYBwU33q8Tch1os2+X0kMg== array-union@^2.1.0: version "2.1.0" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" + resolved "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== arrify@^2.0.1: version "2.0.1" - resolved "https://registry.yarnpkg.com/arrify/-/arrify-2.0.1.tgz#c9655e9331e0abcd588d2a7cad7e9956f66701fa" + resolved "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz" integrity sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug== ast-parents@^0.0.1: version "0.0.1" - resolved "https://registry.yarnpkg.com/ast-parents/-/ast-parents-0.0.1.tgz#508fd0f05d0c48775d9eccda2e174423261e8dd3" + resolved "https://registry.npmjs.org/ast-parents/-/ast-parents-0.0.1.tgz" integrity sha512-XHusKxKz3zoYk1ic8Un640joHbFMhbqneyoZfoKnEGtf2ey9Uh/IdpcQplODdO/kENaMIWsD0nJm4+wX3UNLHA== astral-regex@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" + resolved "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz" integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== balanced-match@^1.0.0: version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" + resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== brace-expansion@^1.1.7: version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" @@ -136,19 +136,19 @@ brace-expansion@^1.1.7: brace-expansion@^2.0.1: version "2.0.1" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" + resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" callsites@^3.0.0: version "3.1.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" + resolved "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== chalk@^2.0.0: version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" + resolved "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" @@ -157,7 +157,7 @@ chalk@^2.0.0: chalk@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" + resolved "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz" integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== dependencies: ansi-styles "^4.1.0" @@ -165,7 +165,7 @@ chalk@^3.0.0: chalk@^4.1.2: version "4.1.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" + resolved "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz" integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== dependencies: ansi-styles "^4.1.0" @@ -173,51 +173,51 @@ chalk@^4.1.2: color-convert@^1.9.0: version "1.9.3" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" + resolved "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" color-convert@^2.0.1: version "2.0.1" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + resolved "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz" integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== dependencies: color-name "~1.1.4" -color-name@1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" - integrity sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw== - color-name@~1.1.4: version "1.1.4" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== +color-name@1.1.3: + version "1.1.3" + resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz" + integrity sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw== + command-exists@^1.2.8: version "1.2.9" - resolved "https://registry.yarnpkg.com/command-exists/-/command-exists-1.2.9.tgz#c50725af3808c8ab0260fd60b01fbfa25b954f69" + resolved "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz" integrity sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w== commander@^10.0.0: version "10.0.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-10.0.0.tgz#71797971162cd3cf65f0b9d24eb28f8d303acdf1" + resolved "https://registry.npmjs.org/commander/-/commander-10.0.0.tgz" integrity sha512-zS5PnTI22FIRM6ylNW8G4Ap0IEOyk62fhLSD0+uHRT9McRCLGpkVNvao4bjimpK/GShynyQkFFxHhwMcETmduA== commander@^8.1.0: version "8.3.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-8.3.0.tgz#4837ea1b2da67b9c616a67afbb0fafee567bca66" + resolved "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz" integrity sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww== concat-map@0.0.1: version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + resolved "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== cosmiconfig@^8.0.0: version "8.1.0" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-8.1.0.tgz#947e174c796483ccf0a48476c24e4fefb7e1aea8" + resolved "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.1.0.tgz" integrity sha512-0tLZ9URlPGU7JsKq0DQOQ3FoRsYX8xDZ7xMiATQfaiGMz7EHowNkbU9u1coAOmnh9p/1ySpm0RB3JNWRXM5GCg== dependencies: import-fresh "^3.2.1" @@ -227,7 +227,7 @@ cosmiconfig@^8.0.0: cross-spawn@^7.0.0: version "7.0.3" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" + resolved "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== dependencies: path-key "^3.1.0" @@ -236,31 +236,31 @@ cross-spawn@^7.0.0: emoji-regex@^8.0.0: version "8.0.0" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" + resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== end-of-stream@^1.1.0: version "1.4.4" - resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" + resolved "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz" integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" error-ex@^1.3.1: version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" + resolved "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" escape-string-regexp@^1.0.5: version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz" integrity sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg== execa@^4.0.0: version "4.1.0" - resolved "https://registry.yarnpkg.com/execa/-/execa-4.1.0.tgz#4e5491ad1572f2f17a77d388c6c857135b22847a" + resolved "https://registry.npmjs.org/execa/-/execa-4.1.0.tgz" integrity sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA== dependencies: cross-spawn "^7.0.0" @@ -275,22 +275,22 @@ execa@^4.0.0: fast-deep-equal@^3.1.1: version "3.1.3" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" + resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== fast-diff@^1.1.2, fast-diff@^1.2.0: version "1.2.0" - resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03" + resolved "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz" integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w== fast-json-stable-stringify@^2.0.0: version "2.1.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" + resolved "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== find-up@^4.1.0: version "4.1.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" + resolved "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz" integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== dependencies: locate-path "^5.0.0" @@ -298,24 +298,24 @@ find-up@^4.1.0: follow-redirects@^1.12.1: version "1.15.2" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13" + resolved "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz" integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA== fs.realpath@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + resolved "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz" integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw== get-stream@^5.0.0: version "5.2.0" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" + resolved "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz" integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== dependencies: pump "^3.0.0" glob@^8.0.3: version "8.1.0" - resolved "https://registry.yarnpkg.com/glob/-/glob-8.1.0.tgz#d388f656593ef708ee3e34640fdfb99a9fd1c33e" + resolved "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz" integrity sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ== dependencies: fs.realpath "^1.0.0" @@ -326,27 +326,27 @@ glob@^8.0.3: has-flag@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" + resolved "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz" integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw== has-flag@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" + resolved "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== human-signals@^1.1.1: version "1.1.1" - resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" + resolved "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz" integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw== ignore@^5.1.4, ignore@^5.2.4: version "5.2.4" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" + resolved "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz" integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== import-fresh@^3.2.1: version "3.3.0" - resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b" + resolved "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz" integrity sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw== dependencies: parent-module "^1.0.0" @@ -354,7 +354,7 @@ import-fresh@^3.2.1: inflight@^1.0.4: version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + resolved "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz" integrity sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA== dependencies: once "^1.3.0" @@ -362,127 +362,127 @@ inflight@^1.0.4: inherits@2: version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + resolved "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== is-arrayish@^0.2.1: version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + resolved "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz" integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== is-fullwidth-code-point@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" + resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== is-stream@^2.0.0: version "2.0.1" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" + resolved "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz" integrity sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg== isexe@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + resolved "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz" integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== js-sha3@0.8.0: version "0.8.0" - resolved "https://registry.yarnpkg.com/js-sha3/-/js-sha3-0.8.0.tgz#b9b7a5da73afad7dedd0f8c463954cbde6818840" + resolved "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz" integrity sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q== js-tokens@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" + resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^4.1.0: version "4.1.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" + resolved "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz" integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== dependencies: argparse "^2.0.1" json-parse-even-better-errors@^2.3.0: version "2.3.1" - resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" + resolved "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== json-schema-traverse@^0.4.1: version "0.4.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" + resolved "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== json-schema-traverse@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2" + resolved "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz" integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== lines-and-columns@^1.1.6: version "1.2.4" - resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" + resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz" integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== locate-path@^5.0.0: version "5.0.0" - resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" + resolved "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz" integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== dependencies: p-locate "^4.1.0" lodash.truncate@^4.4.2: version "4.4.2" - resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193" + resolved "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz" integrity sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw== lodash@^4.17.21: version "4.17.21" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" + resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== lru-cache@^6.0.0: version "6.0.0" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" + resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz" integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== dependencies: yallist "^4.0.0" memorystream@^0.3.1: version "0.3.1" - resolved "https://registry.yarnpkg.com/memorystream/-/memorystream-0.3.1.tgz#86d7090b30ce455d63fbae12dda51a47ddcaf9b2" + resolved "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz" integrity sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw== merge-stream@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" + resolved "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== mimic-fn@^2.1.0: version "2.1.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" + resolved "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== minimatch@^3.0.4: version "3.1.2" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" + resolved "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz" integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== dependencies: brace-expansion "^1.1.7" minimatch@^5.0.1: version "5.1.6" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" + resolved "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz" integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== dependencies: brace-expansion "^2.0.1" mri@^1.1.5: version "1.2.0" - resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b" + resolved "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz" integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA== multimatch@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/multimatch/-/multimatch-4.0.0.tgz#8c3c0f6e3e8449ada0af3dd29efb491a375191b3" + resolved "https://registry.npmjs.org/multimatch/-/multimatch-4.0.0.tgz" integrity sha512-lDmx79y1z6i7RNx0ZGCPq1bzJ6ZoDDKbvh7jxr9SJcWLkShMzXrHbYVpTdnhNM5MXpDUxCQ4DgqVttVXlBgiBQ== dependencies: "@types/minimatch" "^3.0.3" @@ -493,59 +493,59 @@ multimatch@^4.0.0: npm-run-path@^4.0.0: version "4.0.1" - resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" + resolved "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz" integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== dependencies: path-key "^3.0.0" once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + resolved "https://registry.npmjs.org/once/-/once-1.4.0.tgz" integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== dependencies: wrappy "1" onetime@^5.1.0: version "5.1.2" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" + resolved "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz" integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== dependencies: mimic-fn "^2.1.0" os-tmpdir@~1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + resolved "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz" integrity sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g== p-limit@^2.2.0: version "2.3.0" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" + resolved "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz" integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== dependencies: p-try "^2.0.0" p-locate@^4.1.0: version "4.1.0" - resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" + resolved "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz" integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== dependencies: p-limit "^2.2.0" p-try@^2.0.0: version "2.2.0" - resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" + resolved "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== parent-module@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" + resolved "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz" integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== dependencies: callsites "^3.0.0" parse-json@^5.0.0: version "5.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" + resolved "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz" integrity sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg== dependencies: "@babel/code-frame" "^7.0.0" @@ -555,48 +555,48 @@ parse-json@^5.0.0: path-exists@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" + resolved "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz" integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" + resolved "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== path-type@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" + resolved "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== pluralize@^8.0.0: version "8.0.0" - resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1" + resolved "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz" integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA== prettier-linter-helpers@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b" + resolved "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz" integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== dependencies: fast-diff "^1.1.2" -prettier-plugin-solidity@^1.0.0-beta.19: +prettier-plugin-solidity@^1.0.0-alpha.14, prettier-plugin-solidity@^1.0.0-beta.19: version "1.1.3" - resolved "https://registry.yarnpkg.com/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.3.tgz#9a35124f578404caf617634a8cab80862d726cba" + resolved "https://registry.npmjs.org/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.3.tgz" integrity sha512-fQ9yucPi2sBbA2U2Xjh6m4isUTJ7S7QLc/XDDsktqqxYfTwdYKJ0EnnywXHwCGAaYbQNK+HIYPL1OemxuMsgeg== dependencies: "@solidity-parser/parser" "^0.16.0" semver "^7.3.8" solidity-comments-extractor "^0.0.7" -prettier@^2.5.1, prettier@^2.8.3: +"prettier@^1.15.0 || ^2.0.0", prettier@^2.5.1, prettier@^2.8.3, prettier@>=2.0.0, "prettier@>=2.3.0 || >=3.0.0-alpha.0": version "2.8.4" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.4.tgz#34dd2595629bfbb79d344ac4a91ff948694463c3" + resolved "https://registry.npmjs.org/prettier/-/prettier-2.8.4.tgz" integrity sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw== pretty-quick@^3.1.3: version "3.1.3" - resolved "https://registry.yarnpkg.com/pretty-quick/-/pretty-quick-3.1.3.tgz#15281108c0ddf446675157ca40240099157b638e" + resolved "https://registry.npmjs.org/pretty-quick/-/pretty-quick-3.1.3.tgz" integrity sha512-kOCi2FJabvuh1as9enxYmrnBC6tVMoVOenMaBqRfsvBHB0cbpYHjdQEpSglpASDFEXVwplpcGR4CLEaisYAFcA== dependencies: chalk "^3.0.0" @@ -608,7 +608,7 @@ pretty-quick@^3.1.3: pump@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" + resolved "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz" integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== dependencies: end-of-stream "^1.1.0" @@ -616,56 +616,56 @@ pump@^3.0.0: punycode@^2.1.0: version "2.3.0" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.0.tgz#f67fa67c94da8f4d0cfff981aee4118064199b8f" + resolved "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz" integrity sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA== require-from-string@^2.0.2: version "2.0.2" - resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" + resolved "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz" integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== resolve-from@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" + resolved "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== semver@^5.5.0: version "5.7.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" + resolved "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== semver@^6.3.0: version "6.3.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" + resolved "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== semver@^7.3.8: version "7.3.8" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" + resolved "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz" integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== dependencies: lru-cache "^6.0.0" shebang-command@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" + resolved "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz" integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== dependencies: shebang-regex "^3.0.0" shebang-regex@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" + resolved "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== signal-exit@^3.0.2: version "3.0.7" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" + resolved "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz" integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== slice-ansi@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" + resolved "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz" integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== dependencies: ansi-styles "^4.0.0" @@ -674,7 +674,7 @@ slice-ansi@^4.0.0: solc@0.8.18: version "0.8.18" - resolved "https://registry.yarnpkg.com/solc/-/solc-0.8.18.tgz#a05ce8918540eda5f10aa91f0f52f239b9645dad" + resolved "https://registry.npmjs.org/solc/-/solc-0.8.18.tgz" integrity sha512-wVAa2Y3BYd64Aby5LsgS3g6YC2NvZ3bJ+A8TAIAukfVuQb3AjyGrLZpyxQk5YLn14G35uZtSnIgHEpab9klOLQ== dependencies: command-exists "^1.2.8" @@ -687,14 +687,14 @@ solc@0.8.18: solhint-plugin-prettier@^0.0.5: version "0.0.5" - resolved "https://registry.yarnpkg.com/solhint-plugin-prettier/-/solhint-plugin-prettier-0.0.5.tgz#e3b22800ba435cd640a9eca805a7f8bc3e3e6a6b" + resolved "https://registry.npmjs.org/solhint-plugin-prettier/-/solhint-plugin-prettier-0.0.5.tgz" integrity sha512-7jmWcnVshIrO2FFinIvDQmhQpfpS2rRRn3RejiYgnjIE68xO2bvrYvjqVNfrio4xH9ghOqn83tKuTzLjEbmGIA== dependencies: prettier-linter-helpers "^1.0.0" solhint@^3.3.7: version "3.4.0" - resolved "https://registry.yarnpkg.com/solhint/-/solhint-3.4.0.tgz#a7e4f2d73e679cb197a1ca5279aa7534bd323e4d" + resolved "https://registry.npmjs.org/solhint/-/solhint-3.4.0.tgz" integrity sha512-FYEs/LoTxMsWFP/OGsEqR1CBDn3Bn7hrTWsgtjai17MzxITgearIdlo374KKZjjIycu8E2xBcJ+RSWeoBvQmkw== dependencies: "@solidity-parser/parser" "^0.15.0" @@ -719,12 +719,12 @@ solhint@^3.3.7: solidity-comments-extractor@^0.0.7: version "0.0.7" - resolved "https://registry.yarnpkg.com/solidity-comments-extractor/-/solidity-comments-extractor-0.0.7.tgz#99d8f1361438f84019795d928b931f4e5c39ca19" + resolved "https://registry.npmjs.org/solidity-comments-extractor/-/solidity-comments-extractor-0.0.7.tgz" integrity sha512-wciNMLg/Irp8OKGrh3S2tfvZiZ0NEyILfcRCXCD4mp7SgK/i9gzLfhY2hY7VMCQJ3kH9UB9BzNdibIVMchzyYw== string-width@^4.2.3: version "4.2.3" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== dependencies: emoji-regex "^8.0.0" @@ -733,33 +733,33 @@ string-width@^4.2.3: strip-ansi@^6.0.1: version "6.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== dependencies: ansi-regex "^5.0.1" strip-final-newline@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" + resolved "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz" integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== supports-color@^5.3.0: version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" + resolved "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" supports-color@^7.1.0: version "7.2.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" + resolved "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz" integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== dependencies: has-flag "^4.0.0" table@^6.8.1: version "6.8.1" - resolved "https://registry.yarnpkg.com/table/-/table-6.8.1.tgz#ea2b71359fe03b017a5fbc296204471158080bdf" + resolved "https://registry.npmjs.org/table/-/table-6.8.1.tgz" integrity sha512-Y4X9zqrCftUhMeH2EptSSERdVKt/nEdijTOacGD/97EKjhQ/Qs8RTlEGABSJNNN8lac9kheH+af7yAkEWlgneA== dependencies: ajv "^8.0.1" @@ -770,36 +770,36 @@ table@^6.8.1: text-table@^0.2.0: version "0.2.0" - resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" + resolved "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz" integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw== tmp@0.0.33: version "0.0.33" - resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" + resolved "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== dependencies: os-tmpdir "~1.0.2" uri-js@^4.2.2: version "4.4.1" - resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" + resolved "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz" integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== dependencies: punycode "^2.1.0" which@^2.0.1: version "2.0.2" - resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + resolved "https://registry.npmjs.org/which/-/which-2.0.2.tgz" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0" wrappy@1: version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + resolved "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz" integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== yallist@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" + resolved "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== From ac6c8fd4a18b99efa65630f2938c3c5641f99add Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Fri, 24 Apr 2026 16:08:58 -0600 Subject: [PATCH 02/27] build: unlock and accrue --- src/TokenizedStrategy.sol | 395 ++++++++++++++++++++------ src/interfaces/ITokenizedStrategy.sol | 8 + src/test/AccessControl.t.sol | 31 +- src/test/Accounting.t.sol | 9 +- src/test/ProfitLocking.t.sol | 190 ++++++++++++- src/test/Shutdown.t.sol | 4 +- src/test/e2e.t.sol | 12 +- src/test/mocks/MockStorage.sol | 5 +- 8 files changed, 544 insertions(+), 110 deletions(-) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index b57a3e8..037c5f6 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -220,11 +220,14 @@ contract TokenizedStrategy { // Last realized total assets. This is used as the accrual baseline during // write flows and to freeze view math during in-flight external callbacks. uint256 lastTotalAssets; + uint256 profitUnlockingRate; // The rate at which locked profit is unlocking. + uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock. address keeper; // Address given permission to call {report} and {tend}. uint32 profitMaxUnlockTime; uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. address performanceFeeRecipient; // The address to pay the `performanceFee` to. - uint96 lastReport; // The last time accounting synced. + uint96 lastReport; // The last time a report updated the lock schedule. + uint96 lastAccrual; // The last time accounting synced. // Access management variables. @@ -346,8 +349,11 @@ contract TokenizedStrategy { /// @notice Used for fee calculations. uint256 internal constant MAX_BPS = 10_000; - /// @notice Seconds per year for max profit unlocking time. - uint256 internal constant SECONDS_PER_YEAR = 31_556_952; // 365.2425 days + /// @notice Used for profit unlocking rate calculations. + uint256 internal constant MAX_BPS_EXTENDED = 1_000_000_000_000; + /// @notice Holder for dead shares minted against unsolicited initial assets. + address internal constant DEAD_ADDRESS = + 0x000000000000000000000000000000000000dEaD; /** * @dev Custom storage slot that will be used to store the @@ -448,8 +454,9 @@ contract TokenizedStrategy { S.performanceFeeRecipient = _performanceFeeRecipient; // Default to a 10% performance fee. S.performanceFee = 1_000; - // Set last report to this block. + // Initialize both timestamps to the deployment block. S.lastReport = uint96(block.timestamp); + S.lastAccrual = uint96(block.timestamp); // Set the default management address. Can't be 0. require(_management != address(0), "ZERO ADDRESS"); @@ -818,16 +825,16 @@ contract TokenizedStrategy { function _totalSupply( StrategyData storage S ) internal view returns (uint256) { - return S.totalSupply; + return S.totalSupply - _unlockedShares(S); } /// @dev Internal helper to simulate the supply/assets state under the current block latch. function _simulatedTotals( StrategyData storage S ) internal view returns (uint256 supply, uint256 assets) { - supply = S.totalSupply; + supply = _totalSupply(S); - if (S.entered == ENTERED || block.timestamp == S.lastReport) { + if (S.entered == ENTERED || block.timestamp == S.lastAccrual) { return (supply, S.lastTotalAssets); } @@ -865,7 +872,7 @@ contract TokenizedStrategy { uint256 assets, uint256 totalAssets_ ) internal view returns (uint256) { - uint256 supply = S.totalSupply; + uint256 supply = _totalSupply(S); if (assets == 0 || supply == 0) return 0; return assets.mulDiv(supply, totalAssets_ - assets, Math.Rounding.Down); @@ -1088,25 +1095,12 @@ contract TokenizedStrategy { function _accrue( StrategyData storage S ) internal returns (uint256 profit, uint256 loss) { - return _accrue(S, _strategyTotalAssets(), false); - } - - /** - * @dev Synchronize accounting to the strategy's latest asset balance and - * realize any accrued fees or losses. - * - * When `force` is false this can only happen once per block. `report()` - * passes `force = true` so it can refresh accounting again intra-block. - */ - function _accrue( - StrategyData storage S, - uint256 newTotalAssets, - bool force - ) internal returns (uint256 profit, uint256 loss) { - if (!force && block.timestamp == S.lastReport) { + if (block.timestamp == S.lastAccrual) { return (0, 0); } + uint256 newTotalAssets = IBaseStrategy(address(this)) + .strategyTotalAssets(); uint256 oldTotalAssets = S.lastTotalAssets; uint256 totalFees; uint256 protocolFees; @@ -1120,53 +1114,16 @@ contract TokenizedStrategy { // claimable by that first depositor. Mint matching dead shares so // the vault starts from a 1:1 PPS. if (oldTotalAssets == 0 && S.totalSupply == 0) { - _mint(S, address(this), newTotalAssets); + _mint(S, DEAD_ADDRESS, newTotalAssets); } - uint16 fee = S.performanceFee; - if (fee != 0 && oldTotalAssets != 0 && S.totalSupply != 0) { - totalFees = (profit * fee) / MAX_BPS; - - if (totalFees != 0) { - uint256 totalFeeShares = _feeSharesForAmount( - S, - totalFees, - newTotalAssets - ); - - if (totalFeeShares != 0) { - ( - uint16 protocolFeeBps, - address protocolFeesRecipient - ) = IFactory(FACTORY).protocol_fee_config(); - - uint256 protocolFeeShares; - if (protocolFeeBps != 0) { - protocolFees = - (totalFees * protocolFeeBps) / - MAX_BPS; - protocolFeeShares = - (totalFeeShares * protocolFeeBps) / - MAX_BPS; - - if (protocolFeeShares != 0) { - _mint( - S, - protocolFeesRecipient, - protocolFeeShares - ); - } - } - - unchecked { - _mint( - S, - S.performanceFeeRecipient, - totalFeeShares - protocolFeeShares - ); - } - } - } + if (oldTotalAssets != 0) { + (totalFees, protocolFees, ) = _chargeFees( + S, + profit, + newTotalAssets, + true + ); } } else if (oldTotalAssets > newTotalAssets) { unchecked { @@ -1175,21 +1132,92 @@ contract TokenizedStrategy { } S.lastTotalAssets = newTotalAssets; - S.lastReport = uint96(block.timestamp); + S.lastAccrual = uint96(block.timestamp); emit Reported(profit, loss, protocolFees, totalFees - protocolFees); } + /// @dev Mint fee shares for asset-based live accrual. + function _chargeFees( + StrategyData storage S, + uint256 profit, + uint256 newTotalAssets, + bool useNewPps + ) + internal + returns ( + uint256 totalFees, + uint256 protocolFees, + uint256 totalFeeShares + ) + { + uint16 fee = S.performanceFee; + if (fee == 0 || S.totalSupply == 0) return (0, 0, 0); + + // Asses performance fees. + unchecked { + // Get in `asset` for the event. + totalFees = (profit * fee) / MAX_BPS; + } + + // During live accrual there is no gross profit-share bucket to slice, so + // fees must be priced against the new diluted PPS. During locked-profit + // reports we need master-style old-PPS fee shares. + totalFeeShares = useNewPps + ? _feeSharesForAmount(S, totalFees, newTotalAssets) + : _convertToShares(S, totalFees, Math.Rounding.Down); + + (uint16 protocolFeeBps, address protocolFeesRecipient) = IFactory( + FACTORY + ).protocol_fee_config(); + + uint256 protocolFeeShares; + // Check if there is a protocol fee to charge. + if (protocolFeeBps != 0) { + unchecked { + // Calculate protocol fees based on the performance Fees. + protocolFeeShares = (totalFeeShares * protocolFeeBps) / MAX_BPS; + // Need amount in underlying for event. + protocolFees = (totalFees * protocolFeeBps) / MAX_BPS; + } + + // Mint the protocol fees to the recipient. + _mint(S, protocolFeesRecipient, protocolFeeShares); + } + + // Mint the difference to the strategy fee recipient. + unchecked { + _mint( + S, + S.performanceFeeRecipient, + totalFeeShares - protocolFeeShares + ); + } + } + /*////////////////////////////////////////////////////////////// PROFIT REPORTING //////////////////////////////////////////////////////////////*/ /** - * @notice Function for keepers to synchronize accounting to the latest - * strategy asset balance. + * @notice Function for keepers to call to harvest and record all + * profits accrued. + * + * @dev This will account for any gains/losses since the last report + * and charge fees accordingly. * - * @dev This will account for any gains/losses since the last sync and - * charge fees accordingly. + * Any profit over the fees charged will be immediately locked + * so there is no change in PricePerShare. Then slowly unlocked + * over the `maxProfitUnlockTime` each second based on the + * calculated `profitUnlockingRate`. + * + * In case of a loss it will first attempt to offset the loss + * with any remaining locked shares from the last report in + * order to reduce any negative impact to PPS. + * + * Will then recalculate the new time to unlock profits over and the + * rate based on a weighted average of any remaining time from the + * last report and the new amount of shares to be locked. * * @return profit The notional amount of gain if any since the last * report in terms of `asset`. @@ -1202,9 +1230,162 @@ contract TokenizedStrategy { onlyKeepers returns (uint256 profit, uint256 loss) { + // Cache storage pointer since its used repeatedly. StrategyData storage S = _strategyStorage(); - return - _accrue(S, IBaseStrategy(address(this)).harvestAndReport(), true); + + // Tell the strategy to report the real total assets it has. + // It should do all reward selling and redepositing now and + // account for deployed and loose `asset` so we can accurately + // account for all funds including those potentially airdropped + // and then have any profits immediately locked. + uint256 newTotalAssets = IBaseStrategy(address(this)) + .harvestAndReport(); + + uint256 oldTotalAssets = _totalAssets(S); + + // Get the amount of shares we need to burn from previous reports. + uint256 sharesToBurn = _unlockedShares(S); + + // Initialize variables needed throughout. + uint256 totalFees; + uint256 protocolFees; + uint256 sharesToLock; + uint256 _profitMaxUnlockTime = S.profitMaxUnlockTime; + // Calculate profit/loss. + if (newTotalAssets > oldTotalAssets) { + // We have a profit. + unchecked { + profit = newTotalAssets - oldTotalAssets; + } + + // We need to get the equivalent amount of shares + // at the current PPS before any minting or burning. + sharesToLock = _convertToShares(S, profit, Math.Rounding.Down); + uint256 totalFeeShares; + (totalFees, protocolFees, totalFeeShares) = _chargeFees( + S, + profit, + newTotalAssets, + _profitMaxUnlockTime == 0 + ); + + // Check if we are locking profit. + if (_profitMaxUnlockTime != 0) { + // lock (profit - fees) + unchecked { + sharesToLock -= totalFeeShares; + } + + // If we are burning more than re-locking. + if (sharesToBurn > sharesToLock) { + // Burn the difference + unchecked { + _burn(S, address(this), sharesToBurn - sharesToLock); + } + } else if (sharesToLock > sharesToBurn) { + // Mint the shares to lock the strategy. + unchecked { + _mint(S, address(this), sharesToLock - sharesToBurn); + } + } + } + } else { + // Expect we have a loss. + unchecked { + loss = oldTotalAssets - newTotalAssets; + } + + // Check in case `else` was due to being equal. + if (loss != 0) { + // We will try and burn the unlocked shares and as much from any + // pending profit still unlocking to offset the loss to prevent any PPS decline post report. + sharesToBurn = Math.min( + // Cannot burn more than we have. + S.balances[address(this)], + // Try and burn both the shares already unlocked and the amount for the loss. + _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn + ); + } + + // Check if there is anything to burn. + if (sharesToBurn != 0) { + _burn(S, address(this), sharesToBurn); + } + } + + // Update unlocking rate and time to fully unlocked. + uint256 totalLockedShares = S.balances[address(this)]; + if (totalLockedShares != 0) { + uint256 previouslyLockedTime; + uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; + // Check if we need to account for shares still unlocking. + if (_fullProfitUnlockDate > block.timestamp) { + unchecked { + // There will only be previously locked shares if time remains. + // We calculate this here since it should be rare. + previouslyLockedTime = + (_fullProfitUnlockDate - block.timestamp) * + (totalLockedShares - sharesToLock); + } + } + + // newProfitLockingPeriod is a weighted average between the remaining + // time of the previously locked shares and the profitMaxUnlockTime. + uint256 newProfitLockingPeriod = (previouslyLockedTime + + sharesToLock * + _profitMaxUnlockTime) / totalLockedShares; + + // Calculate how many shares unlock per second. + S.profitUnlockingRate = + (totalLockedShares * MAX_BPS_EXTENDED) / + newProfitLockingPeriod; + + // Calculate how long until the full amount of shares is unlocked. + S.fullProfitUnlockDate = uint96( + block.timestamp + newProfitLockingPeriod + ); + } else { + // Only setting this to 0 will turn in the desired effect, + // no need to update profitUnlockingRate. + S.fullProfitUnlockDate = 0; + } + + // Update the new total assets value. + S.lastTotalAssets = newTotalAssets; + S.lastReport = uint96(block.timestamp); + S.lastAccrual = uint96(block.timestamp); + + // Emit event with info + emit Reported( + profit, + loss, + protocolFees, // Protocol fees + totalFees - protocolFees // Performance Fees + ); + } + + /** + * @notice Get how many report-locked shares have unlocked. + * @return . The amount of shares that have unlocked. + */ + function unlockedShares() external view returns (uint256) { + return _unlockedShares(_strategyStorage()); + } + + /// @dev To determine how many report-locked shares have unlocked. + function _unlockedShares( + StrategyData storage S + ) internal view returns (uint256 unlocked) { + uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; + if (_fullProfitUnlockDate > block.timestamp) { + unchecked { + unlocked = + (S.profitUnlockingRate * (block.timestamp - S.lastReport)) / + MAX_BPS_EXTENDED; + } + } else if (_fullProfitUnlockDate != 0) { + unlocked = S.balances[address(this)]; + } } /*////////////////////////////////////////////////////////////// @@ -1353,20 +1534,34 @@ contract TokenizedStrategy { /** * @notice Gets the current time profits are set to unlock over. + * @dev Returns `type(uint256).max` when the packed value was clamped. * @return . The current profit max unlock time. */ function profitMaxUnlockTime() external view returns (uint256) { - return _strategyStorage().profitMaxUnlockTime; + uint256 _profitMaxUnlockTime = _strategyStorage().profitMaxUnlockTime; + if (_profitMaxUnlockTime == type(uint32).max) { + return type(uint256).max; + } + + return _profitMaxUnlockTime; } /** - * @notice The timestamp of the last accounting sync. + * @notice The timestamp of the last report call. * @return . The last report. */ function lastReport() external view returns (uint256) { return uint256(_strategyStorage().lastReport); } + /** + * @notice The timestamp of the last accounting sync. + * @return . The last accrual. + */ + function lastAccrual() external view returns (uint256) { + return uint256(_strategyStorage().lastAccrual); + } + /** * @notice The last realized total assets baseline. * @return . The last stored total assets. @@ -1375,6 +1570,22 @@ contract TokenizedStrategy { return _strategyStorage().lastTotalAssets; } + /** + * @notice Gets the timestamp at which all reported profits will be unlocked. + * @return . The full profit unlocking timestamp. + */ + function fullProfitUnlockDate() external view returns (uint256) { + return uint256(_strategyStorage().fullProfitUnlockDate); + } + + /** + * @notice The per second rate at which reported profits are unlocking. + * @return . The current profit unlocking rate. + */ + function profitUnlockingRate() external view returns (uint256) { + return _strategyStorage().profitUnlockingRate; + } + /** * @notice Get the price per share. * @dev This value offers limited precision. Integrations that require @@ -1495,22 +1706,33 @@ contract TokenizedStrategy { * @notice Sets the time for profits to be unlocked over. * @dev Can only be called by the current `management`. * - * Denominated in seconds and cannot be greater than 1 year. - * * NOTE: Setting to 0 will cause all currently locked profit * to be unlocked instantly and should be done with care. * - * `profitMaxUnlockTime` is stored as a uint32 for packing but can - * be passed in as uint256 for simplicity. + * `profitMaxUnlockTime` is packed as a `uint32`. Larger inputs are + * clamped to `type(uint32).max`, and the getter exposes that sentinel + * as `type(uint256).max`. * * @param _profitMaxUnlockTime New `profitMaxUnlockTime`. */ function setProfitMaxUnlockTime( uint256 _profitMaxUnlockTime ) external onlyManagement { - // Must be less than a year. - require(_profitMaxUnlockTime <= SECONDS_PER_YEAR, "too long"); - _strategyStorage().profitMaxUnlockTime = uint32(_profitMaxUnlockTime); + StrategyData storage S = _strategyStorage(); + uint32 newProfitMaxUnlockTime = _profitMaxUnlockTime > type(uint32).max + ? type(uint32).max + : uint32(_profitMaxUnlockTime); + + if (newProfitMaxUnlockTime == 0) { + uint256 shares = S.balances[address(this)]; + if (shares != 0) { + _burn(S, address(this), shares); + } + S.profitUnlockingRate = 0; + S.fullProfitUnlockDate = 0; + } + + S.profitMaxUnlockTime = newProfitMaxUnlockTime; emit UpdateProfitMaxUnlockTime(_profitMaxUnlockTime); } @@ -1567,6 +1789,9 @@ contract TokenizedStrategy { StrategyData storage S, address account ) internal view returns (uint256) { + if (account == address(this)) { + return S.balances[account] - _unlockedShares(S); + } return S.balances[account]; } diff --git a/src/interfaces/ITokenizedStrategy.sol b/src/interfaces/ITokenizedStrategy.sol index b1cbaf1..584b025 100644 --- a/src/interfaces/ITokenizedStrategy.sol +++ b/src/interfaces/ITokenizedStrategy.sol @@ -128,14 +128,22 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { function performanceFeeRecipient() external view returns (address); + function fullProfitUnlockDate() external view returns (uint256); + + function profitUnlockingRate() external view returns (uint256); + function profitMaxUnlockTime() external view returns (uint256); function lastReport() external view returns (uint256); + function lastAccrual() external view returns (uint256); + function lastTotalAssets() external view returns (uint256); function isShutdown() external view returns (bool); + function unlockedShares() external view returns (uint256); + /*////////////////////////////////////////////////////////////// SETTERS //////////////////////////////////////////////////////////////*/ diff --git a/src/test/AccessControl.t.sol b/src/test/AccessControl.t.sol index cf88248..d6aa107 100644 --- a/src/test/AccessControl.t.sol +++ b/src/test/AccessControl.t.sol @@ -68,9 +68,8 @@ contract AccessControlTest is Setup { assertEq(strategy.performanceFeeRecipient(), _address); } - function test_setProfitMaxUnlockTime(uint32 _amount) public { - // Must be less than 1 year - uint256 amount = bound(uint256(_amount), 1, 31_556_952); + function test_setProfitMaxUnlockTime(uint256 _amount) public { + uint256 amount = bound(_amount, 1, type(uint32).max - 1); vm.expectEmit(true, true, true, true, address(strategy)); emit UpdateProfitMaxUnlockTime(amount); @@ -81,6 +80,18 @@ contract AccessControlTest is Setup { assertEq(strategy.profitMaxUnlockTime(), amount); } + function test_setProfitMaxUnlockTime_clamps(uint256 _amount) public { + uint256 amount = bound(_amount, type(uint32).max, type(uint256).max); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit UpdateProfitMaxUnlockTime(amount); + + vm.prank(management); + strategy.setProfitMaxUnlockTime(amount); + + assertEq(strategy.profitMaxUnlockTime(), type(uint256).max); + } + function test_shutdown() public { assertTrue(!strategy.isShutdown()); @@ -178,12 +189,9 @@ contract AccessControlTest is Setup { function test_settingProfitMaxUnlockTime_reverts( address _address, - uint32 _amount, - uint256 _badAmount + uint256 _amount ) public { - // Must be less than 1 year - uint256 amount = bound(uint256(_amount), 1, 31_556_952); - _badAmount = bound(_badAmount, 31_556_952 + 1, type(uint256).max); + uint256 amount = bound(_amount, 1, type(uint32).max - 1); vm.assume(_address != management); uint256 profitMaxUnlockTime = strategy.profitMaxUnlockTime(); @@ -193,13 +201,6 @@ contract AccessControlTest is Setup { strategy.setProfitMaxUnlockTime(amount); assertEq(strategy.profitMaxUnlockTime(), profitMaxUnlockTime); - - // Can't be more than 1 year of seconds - vm.prank(management); - vm.expectRevert("too long"); - strategy.setProfitMaxUnlockTime(_badAmount); - - assertEq(strategy.profitMaxUnlockTime(), profitMaxUnlockTime); } function test_shutdown_reverts(address _address) public { diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index 9eb24bc..4676b18 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -17,6 +17,7 @@ contract AccountingTest is Setup { _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( _user != address(0) && + _user != 0x000000000000000000000000000000000000dEaD && _user != address(strategy) && _user != keeper && _user != management && @@ -62,6 +63,7 @@ contract AccountingTest is Setup { _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); vm.assume( _user != address(0) && + _user != 0x000000000000000000000000000000000000dEaD && _user != address(strategy) && _user != keeper && _user != management && @@ -300,6 +302,7 @@ contract AccountingTest is Setup { _donation = bound(_donation, minFuzzAmount, maxFuzzAmount); vm.assume( _user != address(0) && + _user != 0x000000000000000000000000000000000000dEaD && _user != address(strategy) && _user != keeper && _user != management && @@ -320,7 +323,11 @@ contract AccountingTest is Setup { mintAndDepositIntoStrategy(strategy, _user, _amount); assertEq(strategy.balanceOf(_user), _amount, "!shares"); - assertEq(strategy.balanceOf(address(strategy)), _donation, "!dead"); + assertEq( + strategy.balanceOf(0x000000000000000000000000000000000000dEaD), + _donation, + "!dead" + ); assertEq(strategy.totalAssets(), _amount + _donation, "!assets"); uint256 before = asset.balanceOf(_user); diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index 5be9db7..f78f5aa 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -42,7 +42,8 @@ contract ProfitLockingTest is Setup { assertEq(reportedProfit, profit, "!profit"); assertEq(reportedLoss, 0, "!loss"); - assertGt(strategy.pricePerShare(), ppsBefore, "!pps"); + assertEq(strategy.pricePerShare(), ppsBefore, "!pps"); + assertGt(strategy.balanceOf(address(strategy)), 0, "!buffer"); assertApproxEq( strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), expectedProtocolFees, @@ -55,6 +56,11 @@ contract ProfitLockingTest is Setup { expectedPerformanceFees, 100 ); + + skip(profitMaxUnlockTime); + + assertGt(strategy.pricePerShare(), ppsBefore, "!unlock"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer cleared"); } function test_reportDoesNotDoubleCharge( @@ -93,6 +99,60 @@ contract ProfitLockingTest is Setup { ); } + function test_reportWithoutUnlockUsesDilutedFeeShares( + address _user, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) + ); + + uint16 protocolFee = 1_000; + uint16 performanceFee = 1_000; + setFees(protocolFee, performanceFee); + + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 totalFeeAssets = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFees = (totalFeeAssets * protocolFee) / MAX_BPS; + uint256 expectedPerformanceFees = totalFeeAssets - expectedProtocolFees; + + asset.mint(address(strategy), profit); + + uint256 ppsBefore = strategy.pricePerShare(); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, profit, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertGt(strategy.pricePerShare(), ppsBefore, "!pps"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFees, + 100 + ); + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFees, + 100 + ); + } + function test_feeSyncOnDepositMatchesLivePrice( address _user, address _depositor, @@ -139,6 +199,134 @@ contract ProfitLockingTest is Setup { assertEq(reportedLoss, 0, "!loss"); } + function test_reportLocksChunkyYieldAfterContinuousAccrual( + address _user, + address _depositor, + uint256 _amount, + uint16 _liveProfitFactor, + uint16 _reportProfitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _liveProfitFactor = uint16( + bound(uint256(_liveProfitFactor), 10, MAX_BPS) + ); + _reportProfitFactor = uint16( + bound(uint256(_reportProfitFactor), 10, MAX_BPS) + ); + vm.assume( + _user != address(0) && + _depositor != address(0) && + _user != _depositor && + _user != address(strategy) && + _depositor != address(strategy) && + _user != address(yieldSource) && + _depositor != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 initialPps = strategy.pricePerShare(); + + uint256 liveProfit = (_amount * _liveProfitFactor) / MAX_BPS; + asset.mint(address(yieldSource), liveProfit); + + skip(1); + + uint256 ppsBeforeSync = strategy.pricePerShare(); + assertGt(ppsBeforeSync, initialPps, "!live pps"); + + asset.mint(_depositor, _amount); + vm.prank(_depositor); + asset.approve(address(strategy), _amount); + + vm.prank(_depositor); + strategy.deposit(_amount, _depositor); + + uint256 reportProfit = (_amount * _reportProfitFactor) / MAX_BPS; + asset.mint(address(strategy), reportProfit); + + uint256 assetsBeforeReport = strategy.totalAssets(); + uint256 ppsBeforeReport = strategy.pricePerShare(); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(assetsBeforeReport, (_amount * 2) + liveProfit, "!assets"); + assertEq(reportedProfit, reportProfit, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertGt(strategy.balanceOf(address(strategy)), 0, "!buffer"); + + skip(profitMaxUnlockTime); + + assertGt(strategy.pricePerShare(), ppsBeforeReport, "!unlock"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer cleared"); + } + + function test_liveAccrualAfterPartialUnlockUsesCurrentSupply( + address _user, + address _depositor, + uint256 _amount, + uint16 _reportProfitFactor, + uint16 _liveProfitFactor, + uint16 _unlockBps + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _reportProfitFactor = uint16( + bound(uint256(_reportProfitFactor), 10, MAX_BPS) + ); + _liveProfitFactor = uint16( + bound(uint256(_liveProfitFactor), 10, MAX_BPS) + ); + _unlockBps = uint16(bound(uint256(_unlockBps), 1, MAX_BPS - 1)); + vm.assume( + _user != address(0) && + _depositor != address(0) && + _user != _depositor && + _user != address(strategy) && + _depositor != address(strategy) && + _user != performanceFeeRecipient && + _depositor != performanceFeeRecipient && + _user != address(yieldSource) && + _depositor != address(yieldSource) + ); + + uint16 performanceFee = 1_000; + setFees(0, performanceFee); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 reportProfit = (_amount * _reportProfitFactor) / MAX_BPS; + asset.mint(address(strategy), reportProfit); + + vm.prank(keeper); + strategy.report(); + + skip((profitMaxUnlockTime * _unlockBps) / MAX_BPS); + + uint256 liveProfit = (_amount * _liveProfitFactor) / MAX_BPS; + uint256 totalFeeAssets = (liveProfit * performanceFee) / MAX_BPS; + asset.mint(address(yieldSource), liveProfit); + + uint256 supplyBeforeSync = strategy.totalSupply(); + uint256 assetsBeforeSync = strategy.totalAssets(); + uint256 expectedFeeShares = (totalFeeAssets * supplyBeforeSync) / + (assetsBeforeSync - totalFeeAssets); + uint256 feeSharesBefore = strategy.balanceOf(performanceFeeRecipient); + + asset.mint(_depositor, _amount); + vm.prank(_depositor); + asset.approve(address(strategy), _amount); + + vm.prank(_depositor); + strategy.deposit(_amount, _depositor); + + assertApproxEq( + strategy.balanceOf(performanceFeeRecipient) - feeSharesBefore, + expectedFeeShares, + 1 + ); + } + function test_settingProfitUnlockTimeDoesNotCreateABuffer( address _user, uint256 _amount, diff --git a/src/test/Shutdown.t.sol b/src/test/Shutdown.t.sol index 9ad80ea..78580cc 100644 --- a/src/test/Shutdown.t.sol +++ b/src/test/Shutdown.t.sol @@ -263,10 +263,12 @@ contract ShutdownTest is Setup { vm.prank(management); strategy.report(); + skip(profitMaxUnlockTime); + vm.prank(_address); strategy.redeem(_amount, _address, _address); - checkStrategyTotals(strategy, 0, 0, 0, 0); + checkStrategyTotals(strategy, 0, 0, 0); assertEq(asset.balanceOf(_address), _amount + profit); } diff --git a/src/test/e2e.t.sol b/src/test/e2e.t.sol index 7546224..8586fb6 100644 --- a/src/test/e2e.t.sol +++ b/src/test/e2e.t.sol @@ -94,8 +94,7 @@ contract e2eTest is Setup { info.strat, info.toDeposit + info.profit, info.toDeposit + info.profit, - 0, - info.toDeposit + 0 ); uint256 before = asset.balanceOf(_address); @@ -197,8 +196,7 @@ contract e2eTest is Setup { info.strat, info.toDeposit + info.profit, info.toDeposit + info.profit, - 0, - info.toDeposit + 0 ); uint256 before = asset.balanceOf(_address); @@ -347,7 +345,8 @@ contract e2eTest is Setup { vm.prank(_address); info.strat.redeem(info.toDeposit, _address, _address); - assertGt(asset.balanceOf(_address) - before, info.toDeposit); + uint256 firstPayout = asset.balanceOf(_address) - before; + assertGt(firstPayout, info.toDeposit); before = asset.balanceOf(_secondAddress); uint256 balance = info.strat.balanceOf(_secondAddress); @@ -355,7 +354,8 @@ contract e2eTest is Setup { vm.prank(_secondAddress); info.strat.redeem(balance, _secondAddress, _secondAddress); - assertLe(asset.balanceOf(_secondAddress) - before, info.toDeposit); + uint256 secondPayout = asset.balanceOf(_secondAddress) - before; + assertLt(secondPayout, firstPayout); assertEq(info.strat.pricePerShare(), wad); checkStrategyTotals(info.strat, 0, 0, 0); diff --git a/src/test/mocks/MockStorage.sol b/src/test/mocks/MockStorage.sol index 2f35c6b..97d681a 100644 --- a/src/test/mocks/MockStorage.sol +++ b/src/test/mocks/MockStorage.sol @@ -24,6 +24,8 @@ contract MockStorage { // Assets data to track the last realized total the strategy held. uint256 lastTotalAssets; + uint256 profitUnlockingRate; + uint96 fullProfitUnlockDate; // Variables for profit reporting. // We use uint96 for time stamps to fit in the same slot as an address. // We will surely all be dead by the time the slot overflows. @@ -31,7 +33,8 @@ contract MockStorage { uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over. uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. address performanceFeeRecipient; // The address to pay the `performanceFee` to. - uint96 lastReport; // The last time accounting synced. + uint96 lastReport; // The last time a report updated the lock schedule. + uint96 lastAccrual; // The last time accounting synced. // Access management variables. From f0c3265cb44b38702e1acb988822e31c8c5dae9f Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Fri, 24 Apr 2026 22:09:21 -0600 Subject: [PATCH 03/27] test: report locking --- foundry.toml | 2 +- src/TokenizedStrategy.sol | 44 +- src/test/Accounting.t.sol | 43 + src/test/ProfitLocking.t.sol | 2299 ++++++++++++++++++++++++- src/test/handlers/StrategyHandler.sol | 11 +- src/test/mocks/MockStrategy.sol | 1 + src/test/mocks/MockYieldSource.sol | 33 +- src/test/utils/Setup.sol | 44 +- 8 files changed, 2442 insertions(+), 35 deletions(-) diff --git a/foundry.toml b/foundry.toml index 005d235..f128616 100644 --- a/foundry.toml +++ b/foundry.toml @@ -12,7 +12,7 @@ remappings = [ fs_permissions = [{ access = "read", path = "./"}] [fuzz] -runs = 10_000 +runs = 10_0 max_test_rejects = 1_000_000 [invariant] diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 037c5f6..ed576e7 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -1129,6 +1129,7 @@ contract TokenizedStrategy { unchecked { loss = oldTotalAssets - newTotalAssets; } + _realizeLoss(S, loss); } S.lastTotalAssets = newTotalAssets; @@ -1195,6 +1196,24 @@ contract TokenizedStrategy { } } + function _realizeLoss(StrategyData storage S, uint256 loss) internal { + uint256 sharesToBurn = _unlockedShares(S); + + // We will try and burn the unlocked shares and as much from any + // pending profit still unlocking to offset the loss to prevent any PPS decline post report. + sharesToBurn = Math.min( + // Cannot burn more than we have. + S.balances[address(this)], + // Try and burn both the shares already unlocked and the amount for the loss. + _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn + ); + + // Check if there is anything to burn. + if (sharesToBurn != 0) { + _burn(S, address(this), sharesToBurn); + } + } + /*////////////////////////////////////////////////////////////// PROFIT REPORTING //////////////////////////////////////////////////////////////*/ @@ -1233,6 +1252,9 @@ contract TokenizedStrategy { // Cache storage pointer since its used repeatedly. StrategyData storage S = _strategyStorage(); + // Accrue to update total assets for non harvestable yield + _accrue(S); + // Tell the strategy to report the real total assets it has. // It should do all reward selling and redepositing now and // account for deployed and loose `asset` so we can accurately @@ -1243,9 +1265,6 @@ contract TokenizedStrategy { uint256 oldTotalAssets = _totalAssets(S); - // Get the amount of shares we need to burn from previous reports. - uint256 sharesToBurn = _unlockedShares(S); - // Initialize variables needed throughout. uint256 totalFees; uint256 protocolFees; @@ -1276,6 +1295,7 @@ contract TokenizedStrategy { sharesToLock -= totalFeeShares; } + uint256 sharesToBurn = _unlockedShares(S); // If we are burning more than re-locking. if (sharesToBurn > sharesToLock) { // Burn the difference @@ -1294,23 +1314,7 @@ contract TokenizedStrategy { unchecked { loss = oldTotalAssets - newTotalAssets; } - - // Check in case `else` was due to being equal. - if (loss != 0) { - // We will try and burn the unlocked shares and as much from any - // pending profit still unlocking to offset the loss to prevent any PPS decline post report. - sharesToBurn = Math.min( - // Cannot burn more than we have. - S.balances[address(this)], - // Try and burn both the shares already unlocked and the amount for the loss. - _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn - ); - } - - // Check if there is anything to burn. - if (sharesToBurn != 0) { - _burn(S, address(this), sharesToBurn); - } + _realizeLoss(S, loss); } // Update unlocking rate and time to fully unlocked. diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index 4676b18..5955f84 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -293,6 +293,49 @@ contract AccountingTest is Setup { assertEq(asset.balanceOf(_user) - before, _amount - loss, "!out"); } + function test_visibleLossSyncsBeforeReportAfterLatchOpens( + address _user, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, 5_000)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + skip(1); + + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + yieldSource.simulateLoss(loss); + + uint256 assetsBeforeReport = strategy.totalAssets(); + uint256 ppsBeforeReport = strategy.pricePerShare(); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(0, loss, 0, 0); + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(0, 0, 0, 0); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq(strategy.totalAssets(), assetsBeforeReport, "!assets"); + assertEq(strategy.pricePerShare(), ppsBeforeReport, "!pps"); + } + function test_initialDonationMintsDeadShares( address _user, uint256 _amount, diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index f78f5aa..b65b46a 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.18; +import "forge-std/console.sol"; import {Setup} from "./utils/Setup.sol"; contract ProfitLockingTest is Setup { @@ -8,6 +9,2066 @@ contract ProfitLockingTest is Setup { super.setUp(); } + function test_gain_NoFeesNoBuffer( + address _address, + uint128 amount, + uint16 _profitFactor + ) public { + uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + profit / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + (profit / 2) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainProtocolFee_NoPerformanceFeeNoBuffer( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set protocol fee to 100 bps so there will always be fees charged over a 10 day period with minFuzzAmount + uint16 protocolFee = 1_000; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + totalExpectedFees + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalExpectedFees + ); + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalExpectedFees + ); + + if (totalExpectedFees > 0) { + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + vm.prank(protocolFeeRecipient); + strategy.redeem( + totalExpectedFees, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainPerformanceFee_NoProtocolNoBuffer( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set perf fee to 10% + uint16 protocolFee = 0; + uint16 performanceFee = 1_000; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + totalExpectedFees + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalExpectedFees + ); + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalExpectedFees + ); + + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + vm.prank(performanceFeeRecipient); + strategy.redeem( + totalExpectedFees, + performanceFeeRecipient, + performanceFeeRecipient + ); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainProtocolFeePerformanceFee_NoBuffer( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set perf fee to 10% protocol fee to 100 bps + uint16 protocolFee = 1_000; + uint16 performanceFee = 1_000; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + // Adjust what the performance fee expects to get when there is a protocol fee. + expectedPerformanceFee = expectedPerformanceFee - expectedProtocolFee; + + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + totalExpectedFees + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalExpectedFees + ); + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalExpectedFees + ); + + if (expectedPerformanceFee > 0) { + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + vm.prank(performanceFeeRecipient); + strategy.redeem( + expectedPerformanceFee, + performanceFeeRecipient, + performanceFeeRecipient + ); + } + + expectedAssetsForFees = strategy.convertToAssets(expectedProtocolFee); + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + expectedProtocolFee + ); + + if (expectedProtocolFee > 0) { + vm.prank(protocolFeeRecipient); + strategy.redeem( + expectedProtocolFee, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainBuffer_noProtocolFeeNoPerformanceFee( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + uint256 newAmount = _amount + profit; + + uint256 secondExpectedSharesForFees = strategy.convertToShares( + expectedProtocolFee + expectedPerformanceFee + ); + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - + ((profit - totalExpectedFees) / 2) + + strategy.convertToShares(profit) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - profit + totalExpectedFees + secondExpectedSharesForFees + ); + + vm.prank(_address); + strategy.redeem(newAmount - profit, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainProtocolFeeBuffer_noPerformanceFee( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set fees + uint16 protocolFee = 1_000; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + uint256 newAmount = _amount + profit; + + uint256 secondExpectedSharesForFees = strategy.convertToShares( + expectedProtocolFee + expectedPerformanceFee + ); + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - + ((profit - totalExpectedFees) / 2) + + strategy.convertToShares(profit) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - profit + totalExpectedFees + secondExpectedSharesForFees + ); + + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + + vm.prank(_address); + strategy.redeem(newAmount - profit, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalExpectedFees + secondExpectedSharesForFees + ); + + checkStrategyTotalsApproxAssets( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalExpectedFees + secondExpectedSharesForFees, + 1 + ); + + uint256 balance = strategy.balanceOf(protocolFeeRecipient); + if (balance > 0) { + assertGt(strategy.pricePerShare(), wad, "pps decreased"); + vm.prank(protocolFeeRecipient); + strategy.redeem( + balance, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainPerformanceFeeBuffer_noProtocolFee( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set fees + uint16 protocolFee = 0; + uint16 performanceFee = 1_000; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + uint256 newAmount = _amount + profit; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + uint256 totalFeeShares = strategy.balanceOf(performanceFeeRecipient) + + strategy.balanceOf(protocolFeeRecipient); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - + ((profit - totalExpectedFees) / 2) + + strategy.convertToShares(profit) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - profit + totalFeeShares + ); + + vm.prank(_address); + strategy.redeem(newAmount - profit, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalFeeShares + ); + + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalFeeShares + ); + + assertGe(strategy.pricePerShare(), wad, "pps decreased"); + + uint256 balance = strategy.balanceOf(performanceFeeRecipient); + vm.prank(performanceFeeRecipient); + strategy.redeem( + balance, + performanceFeeRecipient, + performanceFeeRecipient + ); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainProtocolFeePerformanceFeeBuffer( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set fees + uint16 protocolFee = 1_000; + uint16 performanceFee = 1_000; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + // Adjust what the performance fee expects to get when there is a protocol fee. + expectedPerformanceFee = expectedPerformanceFee - expectedProtocolFee; + + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + uint256 newAmount = _amount + profit; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + uint256 totalFeeShares = strategy.balanceOf(performanceFeeRecipient) + + strategy.balanceOf(protocolFeeRecipient); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - + ((profit - totalExpectedFees) / 2) + + strategy.convertToShares(profit) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + newAmount - profit + totalFeeShares + ); + + vm.prank(_address); + // Use newAmount - profit here to avoid stack to deep + strategy.redeem(newAmount - profit, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalFeeShares + ); + + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalFeeShares + ); + + assertGe(strategy.pricePerShare(), wad, "pps decreased"); + + uint256 balance = strategy.balanceOf(protocolFeeRecipient); + if (balance > 0) { + vm.prank(protocolFeeRecipient); + strategy.redeem( + balance, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + balance = strategy.balanceOf(performanceFeeRecipient); + vm.prank(performanceFeeRecipient); + strategy.redeem( + balance, + performanceFeeRecipient, + performanceFeeRecipient + ); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_loss_NoFeesNoBuffer( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 1, 5_000)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + uint256 expectedProtocolFee = 0; + + createAndCheckLoss(strategy, loss, expectedProtocolFee, true); + + assertRelApproxEq( + strategy.pricePerShare(), + wad - ((wad * _lossFactor) / MAX_BPS), + MAX_BPS / 10 + ); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad - ((wad * _lossFactor) / MAX_BPS), + MAX_BPS / 10 + ); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_lossProtocolFees_NoBuffer( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 1, 5_000)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 1_000; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + uint256 expectedProtocolFee = 0; + + uint256 totalExpectedFees = expectedProtocolFee; + createAndCheckLoss( + strategy, + loss, + expectedProtocolFee, + false // Don't check protocol fees with overall loss + ); + + assertRelApproxEq( + strategy.pricePerShare(), + wad - ((wad * _lossFactor) / MAX_BPS), + MAX_BPS / 10 + ); + + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + totalExpectedFees + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + totalExpectedFees + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad - ((wad * _lossFactor) / MAX_BPS), + MAX_BPS / 10 + ); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + totalExpectedFees + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 balance = strategy.balanceOf(protocolFeeRecipient); + if (balance > 0) { + vm.prank(protocolFeeRecipient); + strategy.redeem( + balance, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_lossBuffer_NoProtocolFees( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, 5_000)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + //uint16 performanceFee = 0; + setFees(protocolFee, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + uint256 expectedProtocolFee = 0; + uint256 expectedPerformanceFee = (loss * 0) / MAX_BPS; + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + + // Simulate an original profit of 2x the loss + createAndCheckProfit( + strategy, + loss * 2, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + checkStrategyTotals( + strategy, + _amount + loss * 2, + _amount + loss * 2, + 0, + _amount + loss * 2 + ); + + // Half way through we should have the full loss still as a buffer + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, loss); + + checkStrategyTotals( + strategy, + _amount + loss * 2, + _amount + loss * 2, + 0, + _amount + loss * 2 + totalExpectedFees - loss + ); + + uint256 newAmount = _amount + loss * 2; + + uint256 secondExpectedSharesForFees = strategy.convertToShares( + expectedProtocolFee + expectedPerformanceFee + ); + + // We will not burn the difference between the remaining buffer and shares it will take post profit to cover it + uint256 toNotBurn = loss - strategy.convertToShares(loss); + createAndCheckLoss(strategy, loss, expectedProtocolFee, true); + + // We should have burned the full buffer + assertApproxEq( + strategy.balanceOf(address(strategy)), + toNotBurn, + 1, + "!strategy bal" + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + checkStrategyTotals( + strategy, + newAmount - loss, + newAmount - loss, + 0, + newAmount - + loss * + 2 + + totalExpectedFees + + secondExpectedSharesForFees + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_lossProtocolFeesBuffer( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, 5_000)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 1_000; + setFees(protocolFee, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + uint256 expectedProtocolFee = 0; + uint256 expectedPerformanceFee = (loss * 0) / MAX_BPS; + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + + // Simulate an original profit of 2x the loss + createAndCheckProfit( + strategy, + loss * 2, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + loss * 2, + _amount + loss * 2, + 0, + _amount + loss * 2 + ); + + // Half way through we should have the full loss still as a buffer + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (loss * 2 - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + loss * 2, + _amount + loss * 2, + 0, + _amount + loss * 2 - ((loss * 2 - totalExpectedFees) / 2) + ); + + uint256 newAmount = _amount + loss * 2; + + uint256 secondExpectedSharesForFees = strategy.convertToShares( + expectedProtocolFee + expectedPerformanceFee + ); + + createAndCheckLoss( + strategy, + loss, + expectedProtocolFee, + false // Don't check protocol fees with overall loss + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + console.log("Current bal ", strategy.balanceOf(address(strategy))); + checkStrategyTotals( + strategy, + newAmount - loss, + newAmount - loss, + 0, + newAmount - + loss * + 2 + + totalExpectedFees + + secondExpectedSharesForFees + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 balance = strategy.balanceOf(protocolFeeRecipient); + if (balance > 0) { + vm.prank(protocolFeeRecipient); + strategy.redeem( + balance, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_NoGainFeesOrBuffer( + address _address, + uint128 amount, + uint16 _profitFactor + ) public { + uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); + _profitFactor = 0; + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + assertApproxEq( + strategy.convertToAssets( + strategy.balanceOf(performanceFeeRecipient) + ), + expectedPerformanceFee, + 100 + ); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(protocolFeeRecipient)), + expectedProtocolFee, + 100 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + profit / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + (profit / 2) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gain_NoFeesNoBuffer_noLocking( + address _address, + uint128 amount, + uint16 _profitFactor + ) public { + uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + + // Set max unlocking time to 0. + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + assertEq(strategy.profitMaxUnlockTime(), 0); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + // All profit should have been unlocked instantly. + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + assertGt(strategy.pricePerShare(), wad, "!pps"); + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + // Nothing should change + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gain_NoFeesNoBuffer_noLocking_withdrawAll( + address _address, + uint128 amount, + uint16 _profitFactor + ) public { + uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + + // Set max unlocking time to 0. + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + assertEq(strategy.profitMaxUnlockTime(), 0); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + // All profit should have been unlocked instantly. + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + assertGt(strategy.pricePerShare(), wad, "!pps"); + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + // Should be able to withdraw all right away + uint256 beforeBalance = asset.balanceOf(_address); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + assertEq(asset.balanceOf(_address), beforeBalance + _amount + profit); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainFees_NoBuffer_noLocking( + address _address, + uint128 amount, + uint16 _profitFactor + ) public { + uint256 _amount = bound(uint256(amount), minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 1_000; + uint16 performanceFee = 1_000; + setFees(protocolFee, performanceFee); + + // Set max unlocking time to 0. + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + assertEq(strategy.profitMaxUnlockTime(), 0); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + { + uint256 expectedPerformanceFee = (profit * performanceFee) / + MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * + protocolFee) / MAX_BPS; + expectedPerformanceFee -= expectedProtocolFee; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + } + + uint256 expectedPerformanceFeeShares = strategy.balanceOf( + performanceFeeRecipient + ); + uint256 expectedProtocolFeeShares = strategy.balanceOf( + protocolFeeRecipient + ); + uint256 totalFeeShares = expectedPerformanceFeeShares + + expectedProtocolFeeShares; + + // All profit should have been unlocked instantly. + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + assertGt(strategy.pricePerShare(), wad, "!pps"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + totalFeeShares + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 expectedAssetsForFees = strategy.convertToAssets( + totalFeeShares + ); + + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + totalFeeShares + ); + + if (expectedPerformanceFeeShares > 0) { + assertGe(strategy.pricePerShare(), wad, "pps decreased"); + + vm.prank(performanceFeeRecipient); + strategy.redeem( + expectedPerformanceFeeShares, + performanceFeeRecipient, + performanceFeeRecipient + ); + } + + expectedAssetsForFees = strategy.convertToAssets( + expectedProtocolFeeShares + ); + + checkStrategyTotals( + strategy, + expectedAssetsForFees, + expectedAssetsForFees, + 0, + expectedProtocolFeeShares + ); + + if (expectedProtocolFeeShares > 0) { + vm.prank(protocolFeeRecipient); + strategy.redeem( + expectedProtocolFeeShares, + protocolFeeRecipient, + protocolFeeRecipient + ); + } + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_gainBuffer_noFees_noLocking_resets( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + // Make sure we have active unlocking + assertGt(strategy.profitUnlockingRate(), 0); + assertGt(strategy.fullProfitUnlockDate(), 0); + assertGt(strategy.balanceOf(address(strategy)), 0); + + // Set max unlocking time to 0. + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + // Make sure it reset all unlocking rates. + assertEq(strategy.profitMaxUnlockTime(), 0); + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + assertEq(strategy.balanceOf(address(strategy)), 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + uint256 newAmount = _amount + profit; + + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + // Should unlock everything right away. + checkStrategyTotals( + strategy, + newAmount + profit, + newAmount + profit, + 0, + _amount + ); + + increaseTimeAndCheckBuffer(strategy, 0, 0); + + vm.prank(_address); + strategy.redeem(newAmount - profit, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_buffer_noGainReport( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + + uint256 expectedPerformanceFee = (profit * performanceFee) / MAX_BPS; + uint256 expectedProtocolFee = (expectedPerformanceFee * protocolFee) / + MAX_BPS; + + uint256 totalExpectedFees = expectedPerformanceFee + + expectedProtocolFee; + createAndCheckProfit( + strategy, + profit, + expectedProtocolFee, + expectedPerformanceFee + ); + + assertEq(strategy.pricePerShare(), wad, "!pps"); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit + ); + + increaseTimeAndCheckBuffer( + strategy, + profitMaxUnlockTime / 2, + (profit - totalExpectedFees) / 2 + ); + + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + // Make sure we have active unlocking + assertGt(strategy.profitUnlockingRate(), 0); + assertGt(strategy.fullProfitUnlockDate(), 0); + assertGt(strategy.balanceOf(address(strategy)), 0); + uint256 pps = strategy.pricePerShare(); + + // Report with no profit or loss + vm.prank(keeper); + strategy.report(); + + // Should be the same as before + assertEq(strategy.pricePerShare(), pps, "pps"); + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + profit - ((profit - totalExpectedFees) / 2) + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + // Everything should be unlocked now. + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + checkStrategyTotals( + strategy, + _amount + profit, + _amount + profit, + 0, + _amount + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + + function test_loss_NoFeesNoBuffer_noUnlock( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 1, 5_000)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != protocolFeeRecipient && + _address != performanceFeeRecipient && + _address != address(yieldSource) + ); + // set all fees to 0 + uint16 protocolFee = 0; + uint16 performanceFee = 0; + setFees(protocolFee, performanceFee); + + // Set max unlocking time to 0. + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + assertEq(strategy.profitMaxUnlockTime(), 0); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + // Increase time to simulate interest being earned + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime, 0); + + uint256 loss = (_amount * _lossFactor) / MAX_BPS; + uint256 expectedProtocolFee = 0; + + createAndCheckLoss(strategy, loss, expectedProtocolFee, true); + + assertEq(strategy.profitUnlockingRate(), 0, "!rate"); + assertEq(strategy.fullProfitUnlockDate(), 0, "date"); + assertRelApproxEq( + strategy.pricePerShare(), + wad - ((wad * _lossFactor) / MAX_BPS), + MAX_BPS / 10 + ); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + ); + + increaseTimeAndCheckBuffer(strategy, profitMaxUnlockTime / 2, 0); + + assertRelApproxEq( + strategy.pricePerShare(), + wad - ((wad * _lossFactor) / MAX_BPS), + MAX_BPS / 10 + ); + + checkStrategyTotals( + strategy, + _amount - loss, + _amount - loss, + 0, + _amount + ); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + checkStrategyTotals(strategy, 0, 0, 0, 0); + + assertEq(strategy.pricePerShare(), wad, "pps reset"); + } + function test_reportRealizesProtocolAndPerformanceFees( address _user, uint256 _amount, @@ -33,7 +2094,7 @@ contract ProfitLockingTest is Setup { uint256 expectedProtocolFees = (totalFeeAssets * protocolFee) / MAX_BPS; uint256 expectedPerformanceFees = totalFeeAssets - expectedProtocolFees; - asset.mint(address(strategy), profit); + queueHarvestProfit(strategy, profit); uint256 ppsBefore = strategy.pricePerShare(); @@ -80,7 +2141,7 @@ contract ProfitLockingTest is Setup { mintAndDepositIntoStrategy(strategy, _user, _amount); uint256 profit = (_amount * _profitFactor) / MAX_BPS; - asset.mint(address(strategy), profit); + queueHarvestProfit(strategy, profit); vm.prank(keeper); strategy.report(); @@ -128,7 +2189,7 @@ contract ProfitLockingTest is Setup { uint256 expectedProtocolFees = (totalFeeAssets * protocolFee) / MAX_BPS; uint256 expectedPerformanceFees = totalFeeAssets - expectedProtocolFees; - asset.mint(address(strategy), profit); + queueHarvestProfit(strategy, profit); uint256 ppsBefore = strategy.pricePerShare(); @@ -244,7 +2305,7 @@ contract ProfitLockingTest is Setup { strategy.deposit(_amount, _depositor); uint256 reportProfit = (_amount * _reportProfitFactor) / MAX_BPS; - asset.mint(address(strategy), reportProfit); + queueHarvestProfit(strategy, reportProfit); uint256 assetsBeforeReport = strategy.totalAssets(); uint256 ppsBeforeReport = strategy.pricePerShare(); @@ -296,7 +2357,7 @@ contract ProfitLockingTest is Setup { mintAndDepositIntoStrategy(strategy, _user, _amount); uint256 reportProfit = (_amount * _reportProfitFactor) / MAX_BPS; - asset.mint(address(strategy), reportProfit); + queueHarvestProfit(strategy, reportProfit); vm.prank(keeper); strategy.report(); @@ -327,6 +2388,234 @@ contract ProfitLockingTest is Setup { ); } + function test_reportDoesNotRelockAlreadyVisibleContinuousYield( + address _user, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(yieldSource), profit); + + skip(1); + + uint256 assetsBeforeReport = strategy.totalAssets(); + uint256 ppsBeforeReport = strategy.pricePerShare(); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(profit, 0, 0, 0); + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(0, 0, 0, 0); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq(strategy.totalAssets(), assetsBeforeReport, "!assets"); + assertGe(strategy.pricePerShare(), ppsBeforeReport, "!pps"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); + } + + function test_reportOnlyLocksChunkyDeltaAfterVisibleContinuousYield( + address _user, + uint256 _amount, + uint16 _liveProfitFactor, + uint16 _reportProfitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _liveProfitFactor = uint16( + bound(uint256(_liveProfitFactor), 10, MAX_BPS) + ); + _reportProfitFactor = uint16( + bound(uint256(_reportProfitFactor), 10, MAX_BPS) + ); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 liveProfit = (_amount * _liveProfitFactor) / MAX_BPS; + uint256 reportProfit = (_amount * _reportProfitFactor) / MAX_BPS; + + asset.mint(address(yieldSource), liveProfit); + + skip(1); + + uint256 assetsBeforeReport = strategy.totalAssets(); + uint256 ppsBeforeReport = strategy.pricePerShare(); + + queueHarvestProfit(strategy, reportProfit); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(liveProfit, 0, 0, 0); + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(reportProfit, 0, 0, 0); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, reportProfit, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq( + strategy.totalAssets(), + assetsBeforeReport + reportProfit, + "!assets" + ); + assertGe(strategy.pricePerShare(), ppsBeforeReport, "!pps"); + assertApproxEq( + strategy.convertToAssets(strategy.balanceOf(address(strategy))), + reportProfit, + 10 + ); + } + + function test_reportOnlyRealizesChunkyLossAfterVisibleContinuousLoss( + address _user, + uint256 _amount, + uint16 _liveLossFactor, + uint16 _reportLossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _liveLossFactor = uint16(bound(uint256(_liveLossFactor), 10, 2_500)); + _reportLossFactor = uint16( + bound(uint256(_reportLossFactor), 10, 2_500) + ); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 liveLoss = (_amount * _liveLossFactor) / MAX_BPS; + uint256 reportLoss = (_amount * _reportLossFactor) / MAX_BPS; + + skip(1); + + yieldSource.simulateLoss(liveLoss); + + uint256 assetsBeforeReport = strategy.totalAssets(); + uint256 ppsBeforeReport = strategy.pricePerShare(); + + queueHarvestLoss(strategy, reportLoss); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(0, liveLoss, 0, 0); + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(0, reportLoss, 0, 0); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, reportLoss, "!loss"); + assertEq( + strategy.totalAssets(), + assetsBeforeReport - reportLoss, + "!assets" + ); + assertLt(strategy.pricePerShare(), ppsBeforeReport, "!pps"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); + } + + function test_reportDoesNotRelockAlreadyVisibleAirdrop( + address _user, + uint256 _amount, + uint16 _airdropFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _airdropFactor = uint16(bound(uint256(_airdropFactor), 10, MAX_BPS)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 airdrop = (_amount * _airdropFactor) / MAX_BPS; + asset.mint(address(strategy), airdrop); + + skip(1); + + uint256 assetsBeforeReport = strategy.totalAssets(); + uint256 ppsBeforeReport = strategy.pricePerShare(); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(airdrop, 0, 0, 0); + vm.expectEmit(true, true, true, true, address(strategy)); + emit Reported(0, 0, 0, 0); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq(strategy.totalAssets(), assetsBeforeReport, "!assets"); + assertGe(strategy.pricePerShare(), ppsBeforeReport, "!pps"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); + } + + function test_airdropAccruesImmediatelyDuringProfitUnlock( + address _user, + uint256 _amount, + uint16 _reportProfitFactor, + uint16 _airdropFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _reportProfitFactor = uint16( + bound(uint256(_reportProfitFactor), 10, MAX_BPS) + ); + _airdropFactor = uint16(bound(uint256(_airdropFactor), 10, MAX_BPS)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 reportProfit = (_amount * _reportProfitFactor) / MAX_BPS; + queueHarvestProfit(strategy, reportProfit); + + vm.prank(keeper); + strategy.report(); + + skip(profitMaxUnlockTime / 2); + + uint256 assetsBeforeAirdrop = strategy.totalAssets(); + uint256 ppsBeforeAirdrop = strategy.pricePerShare(); + + uint256 airdrop = (_amount * _airdropFactor) / MAX_BPS; + asset.mint(address(strategy), airdrop); + + assertEq( + strategy.totalAssets(), + assetsBeforeAirdrop + airdrop, + "!assets" + ); + assertGt(strategy.pricePerShare(), ppsBeforeAirdrop, "!pps"); + } + function test_settingProfitUnlockTimeDoesNotCreateABuffer( address _user, uint256 _amount, diff --git a/src/test/handlers/StrategyHandler.sol b/src/test/handlers/StrategyHandler.sol index 2375cae..998b517 100644 --- a/src/test/handlers/StrategyHandler.sol +++ b/src/test/handlers/StrategyHandler.sol @@ -5,6 +5,7 @@ import "forge-std/console.sol"; import {ExtendedTest} from "../utils/ExtendedTest.sol"; import {Setup, IMockStrategy, ERC20Mock} from "../utils/Setup.sol"; import {LibAddressSet, AddressSet} from "../utils/LibAddressSet.sol"; +import {MockYieldSource} from "../mocks/MockYieldSource.sol"; contract StrategyHandler is ExtendedTest { using LibAddressSet for AddressSet; @@ -125,8 +126,9 @@ contract StrategyHandler is ExtendedTest { function reportProfit(uint256 _amount) public countCall("reportProfit") { _amount = bound(_amount, 1_000, strategy.totalAssets() / 2); - // Simulate earning interest - asset.mint(address(strategy), _amount); + // Queue chunky profit so it only exists after harvestAndReport(). + asset.mint(address(setup.yieldSource()), _amount); + MockYieldSource(address(setup.yieldSource())).queueRewards(_amount); vm.prank(setup.keeper()); (uint256 profit, uint256 loss) = strategy.report(); @@ -139,9 +141,8 @@ contract StrategyHandler is ExtendedTest { function reportLoss(uint256 _amount) public countCall("reportLoss") { _amount = bound(_amount, 0, strategy.totalAssets() / 2); - // Simulate losing money - vm.prank(address(setup.yieldSource())); - asset.transfer(address(69), _amount); + // Queue chunky loss so it only exists after harvestAndReport(). + MockYieldSource(address(setup.yieldSource())).queueLoss(_amount); vm.prank(setup.keeper()); (uint256 profit, uint256 loss) = strategy.report(); diff --git a/src/test/mocks/MockStrategy.sol b/src/test/mocks/MockStrategy.sol index 1eb7bde..f4015c8 100644 --- a/src/test/mocks/MockStrategy.sol +++ b/src/test/mocks/MockStrategy.sol @@ -39,6 +39,7 @@ contract MockStrategy is BaseStrategy { } function _harvestAndReport() internal override returns (uint256) { + MockYieldSource(yieldSource).harvest(); uint256 balance = ERC20(asset).balanceOf(address(this)); if (balance > 0 && !TokenizedStrategy.isShutdown()) { MockYieldSource(yieldSource).deposit(balance); diff --git a/src/test/mocks/MockYieldSource.sol b/src/test/mocks/MockYieldSource.sol index 3af5c2b..1131869 100644 --- a/src/test/mocks/MockYieldSource.sol +++ b/src/test/mocks/MockYieldSource.sol @@ -5,6 +5,10 @@ import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockYieldSource { address public asset; + uint256 public pendingRewards; + uint256 public pendingLoss; + address internal constant LOSS_SINK = + 0x000000000000000000000000000000000000dEaD; constructor(address _asset) { asset = _asset; @@ -15,13 +19,38 @@ contract MockYieldSource { } function withdraw(uint256 _amount) public { - uint256 _balance = ERC20(asset).balanceOf(address(this)); + uint256 _balance = balance(); _amount = _amount > _balance ? _balance : _amount; ERC20(asset).transfer(msg.sender, _amount); } function balance() public view returns (uint256) { - return ERC20(asset).balanceOf(address(this)); + uint256 currentBalance = ERC20(asset).balanceOf(address(this)); + return + currentBalance > pendingRewards + ? currentBalance - pendingRewards + : 0; + } + + function queueRewards(uint256 _amount) public { + pendingRewards += _amount; + } + + function queueLoss(uint256 _amount) public { + pendingLoss += _amount; + } + + function harvest() + public + returns (uint256 harvested, uint256 realizedLoss) + { + harvested = pendingRewards; + realizedLoss = pendingLoss; + pendingRewards = 0; + pendingLoss = 0; + if (realizedLoss > 0) { + ERC20(asset).transfer(LOSS_SINK, realizedLoss); + } } function simulateLoss(uint256 _amount) public { diff --git a/src/test/utils/Setup.sol b/src/test/utils/Setup.sol index b99e787..eeead06 100644 --- a/src/test/utils/Setup.sol +++ b/src/test/utils/Setup.sol @@ -172,6 +172,33 @@ contract Setup is ExtendedTest, IEvents { assertApproxEq(_strategy.totalSupply(), _totalSupply, 1, "!supply"); } + function checkStrategyTotalsApproxAssets( + IMockStrategy _strategy, + uint256 _totalAssets, + uint256 _totalDebt, + uint256 _totalIdle, + uint256 _totalSupply, + uint256 _assetTolerance + ) public { + uint256 _assets = _strategy.totalAssets(); + uint256 _balance = ERC20Mock(_strategy.asset()).balanceOf( + address(_strategy) + ); + uint256 _idle = _balance > _assets ? _assets : _balance; + uint256 _debt = _assets - _idle; + assertApproxEq(_assets, _totalAssets, _assetTolerance, "!totalAssets"); + assertApproxEq(_debt, _totalDebt, _assetTolerance, "!totalDebt"); + assertEq(_idle, _totalIdle, "!totalIdle"); + assertApproxEq( + _assets, + _totalDebt + _totalIdle, + _assetTolerance, + "!Added" + ); + // We give supply a buffer or 1 wei for rounding + assertApproxEq(_strategy.totalSupply(), _totalSupply, 1, "!supply"); + } + // For checks without totalSupply while profit is unlocking function checkStrategyTotals( IMockStrategy _strategy, @@ -198,7 +225,7 @@ contract Setup is ExtendedTest, IEvents { uint256 _performanceFees ) public { uint256 startingAssets = _strategy.totalAssets(); - asset.mint(address(_strategy), profit); + queueHarvestProfit(_strategy, profit); // Check the event matches the expected values vm.expectEmit(true, true, true, true, address(_strategy)); @@ -217,6 +244,19 @@ contract Setup is ExtendedTest, IEvents { assertEq(_strategy.lastReport(), block.timestamp, "last report"); } + function queueHarvestProfit( + IMockStrategy _strategy, + uint256 profit + ) public { + MockYieldSource _yieldSource = MockYieldSource(_strategy.yieldSource()); + ERC20Mock(_strategy.asset()).mint(address(_yieldSource), profit); + _yieldSource.queueRewards(profit); + } + + function queueHarvestLoss(IMockStrategy _strategy, uint256 loss) public { + MockYieldSource(_strategy.yieldSource()).queueLoss(loss); + } + function createAndCheckLoss( IMockStrategy _strategy, uint256 loss, @@ -225,7 +265,7 @@ contract Setup is ExtendedTest, IEvents { ) public { uint256 startingAssets = _strategy.totalAssets(); - yieldSource.simulateLoss(loss); + queueHarvestLoss(_strategy, loss); // Check the event matches the expected values vm.expectEmit(true, true, true, _checkFees, address(_strategy)); emit Reported(0, loss, _protocolFees, 0); From 81d4fc1a9514138bb39f9cf68d04e38bb3dd0c3f Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Sat, 25 Apr 2026 15:29:31 -0600 Subject: [PATCH 04/27] test: losses --- src/test/Accounting.t.sol | 46 +++++++++++++++++++++++++++++ src/test/ProfitLocking.t.sol | 56 ++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index 5955f84..07933a2 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -383,4 +383,50 @@ contract AccountingTest is Setup { assertEq(asset.balanceOf(_user) - before, _amount, "!out"); assertEq(strategy.totalAssets(), _donation, "!remaining"); } + + // Invariant: a view quote (e.g. `previewWithdraw`) must match what the + // same write path would actually execute in the same block. The + // unlatched loss branch of `_simulatedTotals` must simulate the buffer + // burn that `_accrue` would perform on the same observed loss. + function test_previewWithdrawMatchesWritePathOnVisibleLoss() public { + uint256 _amount = 1_000e18; + uint256 profit = 200e18; + uint256 loss = 50e18; + uint256 quoteAssets = 100e18; + address depositor = address(0x5678); + + setFees(0, 0); + + mintAndDepositIntoStrategy(strategy, depositor, _amount); + + // Establish a buffer via report() so a loss has something to burn. + createAndCheckProfit(strategy, profit, 0, 0); + + // Open the latch (so views run the live `_simulatedTotals` branch) + // while keeping the unlock formula in its rate-based regime. + skip(profitMaxUnlockTime / 2); + + // Visible loss not yet accrued. + yieldSource.simulateLoss(loss); + + // Quote BEFORE `_accrue`: must already account for the burn that + // `_accrue` would perform on this loss. + uint256 sharesBefore = strategy.previewWithdraw(quoteAssets); + + // Trigger `_accrue` with no other state change. + // `setPerformanceFeeRecipient` calls `_accrue(S)` first; passing the + // existing recipient makes the rest of the call a no-op. + vm.prank(management); + strategy.setPerformanceFeeRecipient(performanceFeeRecipient); + + // Quote AFTER `_accrue`: latched branch reflects the burned buffer. + // The two quotes must agree — view/write parity in the same block. + uint256 sharesAfter = strategy.previewWithdraw(quoteAssets); + + assertEq( + sharesBefore, + sharesAfter, + "view quote must match write-path quote" + ); + } } diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index b65b46a..57d89c0 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -2652,4 +2652,60 @@ contract ProfitLockingTest is Setup { assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); } + + // Invariant: `balanceOf(address(strategy))` must remain a callable view + // and never underflow, even after `_accrue` has burned the locked-profit + // buffer to absorb a mid-unlock-window loss. `unlockedShares()` must + // never exceed `S.balances[address(this)]`. + function test_balanceOfStrategySurvivesLossBurnDuringUnlockWindow() + public + { + uint256 _amount = 1_000e18; + uint256 profit = 200e18; + uint256 loss = 800e18; + address depositor = address(0x1234); + + setFees(0, 0); + + mintAndDepositIntoStrategy(strategy, depositor, _amount); + + // Lock `profit` into the strategy buffer over `profitMaxUnlockTime`. + createAndCheckProfit(strategy, profit, 0, 0); + assertEq(strategy.balanceOf(address(strategy)), profit, "buffer at T0"); + + // Move to the middle of the unlock window — half the buffer counts as + // unlocked under the rate formula. + skip(profitMaxUnlockTime / 2); + + uint256 unlockedMid = strategy.unlockedShares(); + assertGt(unlockedMid, 0, "some unlocked"); + assertEq( + strategy.balanceOf(address(strategy)), + profit - unlockedMid, + "balanceOf strategy mid-window" + ); + + // Yield-source loss large enough that the burn maxes out at + // `S.balances[strategy]` and drains the entire buffer. + yieldSource.simulateLoss(loss); + + // Trigger `_accrue` via a normal redeem — `_accrue` calls + // `_realizeLoss` which burns from `S.balances[address(this)]`. + vm.prank(depositor); + strategy.redeem(100e18, depositor, depositor); + + // After the burn the unlock accounting must stay consistent: the + // unlocked-shares figure cannot exceed the strategy's actual balance, + // and `balanceOf(strategy)` must still be readable. + assertLe( + strategy.unlockedShares(), + strategy.balanceOf(address(strategy)) + strategy.unlockedShares(), + "unlockedShares > strategy balance" + ); + assertEq( + strategy.balanceOf(address(strategy)), + 0, + "buffer fully drained" + ); + } } From 59e95998cbf33a7674b97aa6e90ac0393831e095 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Sat, 25 Apr 2026 21:22:31 -0600 Subject: [PATCH 05/27] fix: loss checks burn shares --- src/TokenizedStrategy.sol | 133 ++++++++++++++++++++++++++++------- src/test/ProfitLocking.t.sol | 4 +- 2 files changed, 107 insertions(+), 30 deletions(-) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index ed576e7..6dda98b 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -840,6 +840,20 @@ contract TokenizedStrategy { assets = _strategyTotalAssets(); if (assets <= S.lastTotalAssets) { + if (assets < S.lastTotalAssets) { + uint256 loss; + unchecked { + loss = S.lastTotalAssets - assets; + } + + (uint256 lockedBurn, ) = _lossBurnState( + S, + loss, + supply, + S.lastTotalAssets + ); + supply -= lockedBurn; + } return (supply, assets); } @@ -856,7 +870,12 @@ contract TokenizedStrategy { if (fee != 0 && supply != 0) { uint256 totalFees = (profit * fee) / MAX_BPS; if (totalFees != 0) { - supply += _feeSharesForAmount(S, totalFees, assets); + supply += _convertToSharesFromTotals( + totalFees, + supply, + assets - totalFees, + Math.Rounding.Down + ); } } } @@ -866,16 +885,58 @@ contract TokenizedStrategy { return IBaseStrategy(address(this)).strategyTotalAssets(); } - /// @dev Calculates shares that represent `assets` after fee minting dilution. - function _feeSharesForAmount( + /// @dev Returns the loss burn split between already-unlocked and still-locked shares. + function _lossBurnState( StrategyData storage S, - uint256 assets, + uint256 loss, + uint256 supply, uint256 totalAssets_ - ) internal view returns (uint256) { - uint256 supply = _totalSupply(S); - if (assets == 0 || supply == 0) return 0; + ) internal view returns (uint256 lockedBurn, uint256 totalBurn) { + uint256 buffer = S.balances[address(this)]; + if (buffer == 0) return (0, 0); + + uint256 unlocked = _unlockedShares(S); + if (unlocked > buffer) { + unlocked = buffer; + } + + uint256 lossShares = _convertToSharesFromTotals( + loss, + supply, + totalAssets_, + Math.Rounding.Down + ); - return assets.mulDiv(supply, totalAssets_ - assets, Math.Rounding.Down); + unchecked { + lockedBurn = Math.min(buffer - unlocked, lossShares); + totalBurn = unlocked + lockedBurn; + } + } + + /// @dev Converts using an explicit supply/assets snapshot. + function _convertToSharesFromTotals( + uint256 assets, + uint256 supply, + uint256 totalAssets_, + Math.Rounding _rounding + ) internal pure returns (uint256) { + if (supply == 0) return assets; + if (totalAssets_ == 0) return 0; + + return assets.mulDiv(supply, totalAssets_, _rounding); + } + + /// @dev Converts using an explicit supply/assets snapshot. + function _convertToAssetsFromTotals( + uint256 shares, + uint256 supply, + uint256 totalAssets_, + Math.Rounding _rounding + ) internal pure returns (uint256) { + return + supply == 0 + ? shares + : shares.mulDiv(totalAssets_, supply, _rounding); } /// @dev Internal implementation of {convertToShares}. @@ -886,12 +947,13 @@ contract TokenizedStrategy { ) internal view returns (uint256) { (uint256 totalSupply_, uint256 totalAssets_) = _simulatedTotals(S); // If supply is 0, PPS = 1. - if (totalSupply_ == 0) return assets; - - // If assets are 0 but supply is not PPS = 0. - if (totalAssets_ == 0) return 0; - - return assets.mulDiv(totalSupply_, totalAssets_, _rounding); + return + _convertToSharesFromTotals( + assets, + totalSupply_, + totalAssets_, + _rounding + ); } /// @dev Internal implementation of {convertToAssets}. @@ -903,9 +965,7 @@ contract TokenizedStrategy { (uint256 supply, uint256 totalAssets_) = _simulatedTotals(S); return - supply == 0 - ? shares - : shares.mulDiv(totalAssets_, supply, _rounding); + _convertToAssetsFromTotals(shares, supply, totalAssets_, _rounding); } /// @dev Internal implementation of {maxDeposit}. @@ -1130,6 +1190,7 @@ contract TokenizedStrategy { loss = oldTotalAssets - newTotalAssets; } _realizeLoss(S, loss); + _syncUnlockScheduleAfterLoss(S); } S.lastTotalAssets = newTotalAssets; @@ -1165,7 +1226,12 @@ contract TokenizedStrategy { // fees must be priced against the new diluted PPS. During locked-profit // reports we need master-style old-PPS fee shares. totalFeeShares = useNewPps - ? _feeSharesForAmount(S, totalFees, newTotalAssets) + ? _convertToSharesFromTotals( + totalFees, + _totalSupply(S), + newTotalAssets - totalFees, + Math.Rounding.Down + ) : _convertToShares(S, totalFees, Math.Rounding.Down); (uint16 protocolFeeBps, address protocolFeesRecipient) = IFactory( @@ -1197,15 +1263,11 @@ contract TokenizedStrategy { } function _realizeLoss(StrategyData storage S, uint256 loss) internal { - uint256 sharesToBurn = _unlockedShares(S); - - // We will try and burn the unlocked shares and as much from any - // pending profit still unlocking to offset the loss to prevent any PPS decline post report. - sharesToBurn = Math.min( - // Cannot burn more than we have. - S.balances[address(this)], - // Try and burn both the shares already unlocked and the amount for the loss. - _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn + (, uint256 sharesToBurn) = _lossBurnState( + S, + loss, + _totalSupply(S), + S.lastTotalAssets ); // Check if there is anything to burn. @@ -1214,6 +1276,23 @@ contract TokenizedStrategy { } } + /// @dev Re-seeds unlock accounting after `_accrue` burns buffer shares for a loss. + function _syncUnlockScheduleAfterLoss(StrategyData storage S) internal { + uint256 totalLockedShares = S.balances[address(this)]; + S.lastReport = uint96(block.timestamp); + uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; + + if (_fullProfitUnlockDate > block.timestamp && totalLockedShares != 0) { + unchecked { + S.profitUnlockingRate = + (totalLockedShares * MAX_BPS_EXTENDED) / + (_fullProfitUnlockDate - block.timestamp); + } + } else { + S.profitUnlockingRate = 0; + } + } + /*////////////////////////////////////////////////////////////// PROFIT REPORTING //////////////////////////////////////////////////////////////*/ diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index 57d89c0..087dc01 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -2657,9 +2657,7 @@ contract ProfitLockingTest is Setup { // and never underflow, even after `_accrue` has burned the locked-profit // buffer to absorb a mid-unlock-window loss. `unlockedShares()` must // never exceed `S.balances[address(this)]`. - function test_balanceOfStrategySurvivesLossBurnDuringUnlockWindow() - public - { + function test_balanceOfStrategySurvivesLossBurnDuringUnlockWindow() public { uint256 _amount = 1_000e18; uint256 profit = 200e18; uint256 loss = 800e18; From e8112050b4b2cf82a974cc30ac5827b29fd1112b Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Sun, 26 Apr 2026 15:53:03 -0600 Subject: [PATCH 06/27] fix: cleanups --- src/TokenizedStrategy.sol | 129 +++++++++++++++---------------- src/test/utils/BaseInvariant.sol | 38 +++++++++ 2 files changed, 100 insertions(+), 67 deletions(-) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 6dda98b..f9a6f75 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -456,7 +456,8 @@ contract TokenizedStrategy { S.performanceFee = 1_000; // Initialize both timestamps to the deployment block. S.lastReport = uint96(block.timestamp); - S.lastAccrual = uint96(block.timestamp); + // -1 to not allow first deposit inflation + S.lastAccrual = uint96(block.timestamp - 1); // Set the default management address. Can't be 0. require(_management != address(0), "ZERO ADDRESS"); @@ -822,6 +823,8 @@ contract TokenizedStrategy { } /// @dev Internal implementation of {totalSupply}. + /// @notice We don't increase totalSupply until actual shares are minted. + /// This can cause disconnection between conversions done manually function _totalSupply( StrategyData storage S ) internal view returns (uint256) { @@ -838,38 +841,20 @@ contract TokenizedStrategy { return (supply, S.lastTotalAssets); } - assets = _strategyTotalAssets(); - if (assets <= S.lastTotalAssets) { - if (assets < S.lastTotalAssets) { - uint256 loss; - unchecked { - loss = S.lastTotalAssets - assets; - } - - (uint256 lockedBurn, ) = _lossBurnState( - S, - loss, - supply, - S.lastTotalAssets - ); - supply -= lockedBurn; - } - return (supply, assets); - } - - uint256 profit; - unchecked { - profit = assets - S.lastTotalAssets; - } - if (S.lastTotalAssets == 0 && supply == 0) { return (assets, assets); } - uint16 fee = S.performanceFee; - if (fee != 0 && supply != 0) { - uint256 totalFees = (profit * fee) / MAX_BPS; - if (totalFees != 0) { + assets = _strategyTotalAssets(); + if (assets > S.lastTotalAssets) { + uint256 profit; + unchecked { + profit = assets - S.lastTotalAssets; + } + + uint16 fee = S.performanceFee; + if (fee != 0 && supply != 0) { + uint256 totalFees = (profit * fee) / MAX_BPS; supply += _convertToSharesFromTotals( totalFees, supply, @@ -877,6 +862,21 @@ contract TokenizedStrategy { Math.Rounding.Down ); } + } else if (assets < S.lastTotalAssets) { + uint256 loss; + unchecked { + loss = S.lastTotalAssets - assets; + } + + (uint256 lockedBurn, ) = _lossBurnState( + S, + loss, + supply, + S.lastTotalAssets + ); + supply -= lockedBurn; + + return (supply, assets); } } @@ -885,34 +885,6 @@ contract TokenizedStrategy { return IBaseStrategy(address(this)).strategyTotalAssets(); } - /// @dev Returns the loss burn split between already-unlocked and still-locked shares. - function _lossBurnState( - StrategyData storage S, - uint256 loss, - uint256 supply, - uint256 totalAssets_ - ) internal view returns (uint256 lockedBurn, uint256 totalBurn) { - uint256 buffer = S.balances[address(this)]; - if (buffer == 0) return (0, 0); - - uint256 unlocked = _unlockedShares(S); - if (unlocked > buffer) { - unlocked = buffer; - } - - uint256 lossShares = _convertToSharesFromTotals( - loss, - supply, - totalAssets_, - Math.Rounding.Down - ); - - unchecked { - lockedBurn = Math.min(buffer - unlocked, lossShares); - totalBurn = unlocked + lockedBurn; - } - } - /// @dev Converts using an explicit supply/assets snapshot. function _convertToSharesFromTotals( uint256 assets, @@ -1159,8 +1131,7 @@ contract TokenizedStrategy { return (0, 0); } - uint256 newTotalAssets = IBaseStrategy(address(this)) - .strategyTotalAssets(); + uint256 newTotalAssets = _strategyTotalAssets(); uint256 oldTotalAssets = S.lastTotalAssets; uint256 totalFees; uint256 protocolFees; @@ -1225,14 +1196,12 @@ contract TokenizedStrategy { // During live accrual there is no gross profit-share bucket to slice, so // fees must be priced against the new diluted PPS. During locked-profit // reports we need master-style old-PPS fee shares. - totalFeeShares = useNewPps - ? _convertToSharesFromTotals( - totalFees, - _totalSupply(S), - newTotalAssets - totalFees, - Math.Rounding.Down - ) - : _convertToShares(S, totalFees, Math.Rounding.Down); + totalFeeShares = _convertToSharesFromTotals( + totalFees, + _totalSupply(S), + useNewPps ? newTotalAssets - totalFees : S.lastTotalAssets, + Math.Rounding.Down + ); (uint16 protocolFeeBps, address protocolFeesRecipient) = IFactory( FACTORY @@ -1276,6 +1245,32 @@ contract TokenizedStrategy { } } + /// @dev Returns the loss burn split between already-unlocked and still-locked shares. + function _lossBurnState( + StrategyData storage S, + uint256 loss, + uint256 supply, + uint256 totalAssets_ + ) internal view returns (uint256 lockedBurn, uint256 totalBurn) { + uint256 buffer = S.balances[address(this)]; + if (buffer == 0) return (0, 0); + + uint256 unlocked = _unlockedShares(S); + if (unlocked >= buffer) return (0, buffer); + + uint256 lossShares = _convertToSharesFromTotals( + loss, + supply, + totalAssets_, + Math.Rounding.Down + ); + + unchecked { + lockedBurn = Math.min(buffer - unlocked, lossShares); + totalBurn = unlocked + lockedBurn; + } + } + /// @dev Re-seeds unlock accounting after `_accrue` burns buffer shares for a loss. function _syncUnlockScheduleAfterLoss(StrategyData storage S) internal { uint256 totalLockedShares = S.balances[address(this)]; diff --git a/src/test/utils/BaseInvariant.sol b/src/test/utils/BaseInvariant.sol index ec3c7c1..f330da2 100644 --- a/src/test/utils/BaseInvariant.sol +++ b/src/test/utils/BaseInvariant.sol @@ -70,4 +70,42 @@ abstract contract BaseInvariant is Setup { yieldSource.balance() + asset.balanceOf(address(strategy)) ); } + + function assert_unlockingTime() public { + uint256 unlockingDate = strategy.fullProfitUnlockDate(); + uint256 balance = strategy.balanceOf(address(strategy)); + uint256 unlockedShares = strategy.unlockedShares(); + if (unlockingDate != 0 && strategy.profitUnlockingRate() > 0) { + if (block.timestamp == strategy.lastReport()) { + assertEq(unlockedShares, 0); + assertGt(balance, 0); + } else if (block.timestamp < unlockingDate) { + assertGt(unlockedShares, 0); + assertGt(balance, 0); + } else { + // We should have unlocked full balance + assertEq(balance, 0); + assertGt(unlockedShares, 0); + } + } else { + assertEq(balance, 0); + } + } + + function assert_unlockedShares() public { + uint256 unlockedShares = strategy.unlockedShares(); + uint256 fullBalance = strategy.balanceOf(address(strategy)) + + unlockedShares; + uint256 unlockingDate = strategy.fullProfitUnlockDate(); + if ( + unlockingDate != 0 && + strategy.profitUnlockingRate() > 0 && + block.timestamp < unlockingDate + ) { + assertLt(unlockedShares, fullBalance); + } else { + assertEq(unlockedShares, fullBalance); + assertEq(strategy.balanceOf(address(strategy)), 0); + } + } } From 78db3fa307e1972b47e2f27f48a9526e7969e86a Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Sun, 26 Apr 2026 15:53:30 -0600 Subject: [PATCH 07/27] chore: optimize --- foundry.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/foundry.toml b/foundry.toml index f128616..8e6b883 100644 --- a/foundry.toml +++ b/foundry.toml @@ -4,6 +4,8 @@ out = 'out' libs = ['lib'] solc = "0.8.18" evm_version = "paris" +optimize = true +optimizer_runs = 200 remappings = [ 'forge-std/=lib/forge-std/src/', From 1ef546fb0736421ff9e640a6fea58b05c5b4fcb9 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Sun, 26 Apr 2026 20:11:14 -0600 Subject: [PATCH 08/27] chore: init function --- src/BaseStrategy.sol | 10 ++++++---- src/TokenizedStrategy.sol | 24 ++++++++++++------------ src/test/Accounting.t.sol | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 16 deletions(-) diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 4ecf794..8591498 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -137,11 +137,11 @@ abstract contract BaseStrategy { * @param _name Name the strategy will use. */ constructor(address _asset, string memory _name) { - asset = ERC20(_asset); - - // Set instance of the implementation for internal use. - TokenizedStrategy = ITokenizedStrategy(address(this)); + (asset, TokenizedStrategy) = _initialize(_asset, _name); + } + /// @dev Internal function to initialize the strategy. + function _initialize(address _asset, string memory _name) internal virtual returns (ERC20, ITokenizedStrategy) { // Initialize the strategy's storage variables. _delegateCall( abi.encodeCall( @@ -160,6 +160,8 @@ abstract contract BaseStrategy { tokenizedStrategyAddress ) } + + return (ERC20(_asset), ITokenizedStrategy(address(this))); } /*////////////////////////////////////////////////////////////// diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index f9a6f75..b292c81 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -569,6 +569,7 @@ contract TokenizedStrategy { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); _accrue(S); + require( assets <= _maxWithdraw(S, owner), "ERC4626: withdraw more than max" @@ -620,6 +621,7 @@ contract TokenizedStrategy { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); _accrue(S); + require( shares <= _maxRedeem(S, owner), "ERC4626: redeem more than max" @@ -837,15 +839,14 @@ contract TokenizedStrategy { ) internal view returns (uint256 supply, uint256 assets) { supply = _totalSupply(S); - if (S.entered == ENTERED || block.timestamp == S.lastAccrual) { + if (S.entered == ENTERED || block.timestamp == S.lastAccrual) return (supply, S.lastTotalAssets); - } - - if (S.lastTotalAssets == 0 && supply == 0) { - return (assets, assets); - } assets = _strategyTotalAssets(); + + if (S.lastTotalAssets == 0) + return (supply == 0 ? assets : supply, assets); + if (assets > S.lastTotalAssets) { uint256 profit; unchecked { @@ -875,8 +876,6 @@ contract TokenizedStrategy { S.lastTotalAssets ); supply -= lockedBurn; - - return (supply, assets); } } @@ -1193,9 +1192,10 @@ contract TokenizedStrategy { totalFees = (profit * fee) / MAX_BPS; } - // During live accrual there is no gross profit-share bucket to slice, so - // fees must be priced against the new diluted PPS. During locked-profit - // reports we need master-style old-PPS fee shares. + // Get fee shares based on PPS that the txn will end on. + // During live accrual or when profit unlock is 0, + // we use the new diluted PPS. During locked-profit + // reports we need to use the old PPS since it does not change. totalFeeShares = _convertToSharesFromTotals( totalFees, _totalSupply(S), @@ -1354,6 +1354,7 @@ contract TokenizedStrategy { // We need to get the equivalent amount of shares // at the current PPS before any minting or burning. sharesToLock = _convertToShares(S, profit, Math.Rounding.Down); + uint256 totalFeeShares; (totalFees, protocolFees, totalFeeShares) = _chargeFees( S, @@ -1431,7 +1432,6 @@ contract TokenizedStrategy { // Update the new total assets value. S.lastTotalAssets = newTotalAssets; S.lastReport = uint96(block.timestamp); - S.lastAccrual = uint96(block.timestamp); // Emit event with info emit Reported( diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index 07933a2..cd3ca38 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -384,6 +384,43 @@ contract AccountingTest is Setup { assertEq(strategy.totalAssets(), _donation, "!remaining"); } + function test_zeroAssetRecoveryIsFeeFreeAndPreviewMatchesDeposit() public { + address depositor = address(0xA11CE); + address recoveryDepositor = address(0xB0B); + uint256 amount = 100e18; + + setFees(0, 1_000); + mintAndDepositIntoStrategy(strategy, depositor, amount); + + skip(1); + yieldSource.simulateLoss(amount); + + vm.prank(keeper); + strategy.report(); + + assertEq(strategy.totalAssets(), 0, "!zero assets"); + assertEq(strategy.totalSupply(), amount, "!supply remains"); + + asset.mint(address(yieldSource), amount); + skip(1); + + uint256 preview = strategy.previewDeposit(amount); + assertEq(preview, amount, "!fee-free preview"); + + asset.mint(recoveryDepositor, amount); + vm.prank(recoveryDepositor); + asset.approve(address(strategy), amount); + + vm.prank(recoveryDepositor); + uint256 minted = strategy.deposit(amount, recoveryDepositor); + + assertEq(minted, preview, "!preview"); + assertEq(minted, amount, "!shares"); + assertEq(strategy.balanceOf(performanceFeeRecipient), 0, "!fees"); + assertEq(strategy.totalAssets(), amount * 2, "!assets"); + assertEq(strategy.totalSupply(), amount * 2, "!supply"); + } + // Invariant: a view quote (e.g. `previewWithdraw`) must match what the // same write path would actually execute in the same block. The // unlatched loss branch of `_simulatedTotals` must simulate the buffer From a9d7a772986a638a1058423d32e3452c6451d4ba Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Mon, 18 May 2026 15:58:24 -0600 Subject: [PATCH 09/27] feat: distinguish accrual events from reports --- src/TokenizedStrategy.sol | 13 ++++++++++++- src/interfaces/IEvents.sol | 7 +++++++ src/interfaces/ITokenizedStrategy.sol | 7 +++++++ src/test/Accounting.t.sol | 2 +- src/test/ProfitLocking.t.sol | 8 ++++---- 5 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index b292c81..4e4946e 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -104,6 +104,17 @@ contract TokenizedStrategy { uint256 performanceFees ); + /** + * @notice Emitted when the strategy accrues `profit` or `loss` outside of + * an explicit report and `performanceFees` and `protocolFees` are paid out. + */ + event Accrued( + uint256 profit, + uint256 loss, + uint256 protocolFees, + uint256 performanceFees + ); + /** * @notice Emitted when the 'performanceFeeRecipient' address is * updated to 'newPerformanceFeeRecipient'. @@ -1166,7 +1177,7 @@ contract TokenizedStrategy { S.lastTotalAssets = newTotalAssets; S.lastAccrual = uint96(block.timestamp); - emit Reported(profit, loss, protocolFees, totalFees - protocolFees); + emit Accrued(profit, loss, protocolFees, totalFees - protocolFees); } /// @dev Mint fee shares for asset-based live accrual. diff --git a/src/interfaces/IEvents.sol b/src/interfaces/IEvents.sol index c4046d9..bc6d1fb 100644 --- a/src/interfaces/IEvents.sol +++ b/src/interfaces/IEvents.sol @@ -32,6 +32,13 @@ interface IEvents { uint256 performanceFees ); + event Accrued( + uint256 profit, + uint256 loss, + uint256 protocolFees, + uint256 performanceFees + ); + /** * @notice Emitted when the 'performanceFeeRecipient' address is * updated to 'newPerformanceFeeRecipient'. diff --git a/src/interfaces/ITokenizedStrategy.sol b/src/interfaces/ITokenizedStrategy.sol index 584b025..ea5f9db 100644 --- a/src/interfaces/ITokenizedStrategy.sol +++ b/src/interfaces/ITokenizedStrategy.sol @@ -26,6 +26,13 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { uint256 performanceFees ); + event Accrued( + uint256 profit, + uint256 loss, + uint256 protocolFees, + uint256 performanceFees + ); + event UpdatePerformanceFeeRecipient( address indexed newPerformanceFeeRecipient ); diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index cd3ca38..afd1406 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -323,7 +323,7 @@ contract AccountingTest is Setup { uint256 ppsBeforeReport = strategy.pricePerShare(); vm.expectEmit(true, true, true, true, address(strategy)); - emit Reported(0, loss, 0, 0); + emit Accrued(0, loss, 0, 0); vm.expectEmit(true, true, true, true, address(strategy)); emit Reported(0, 0, 0, 0); diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index 087dc01..c2c047a 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -2413,7 +2413,7 @@ contract ProfitLockingTest is Setup { uint256 ppsBeforeReport = strategy.pricePerShare(); vm.expectEmit(true, true, true, true, address(strategy)); - emit Reported(profit, 0, 0, 0); + emit Accrued(profit, 0, 0, 0); vm.expectEmit(true, true, true, true, address(strategy)); emit Reported(0, 0, 0, 0); @@ -2462,7 +2462,7 @@ contract ProfitLockingTest is Setup { queueHarvestProfit(strategy, reportProfit); vm.expectEmit(true, true, true, true, address(strategy)); - emit Reported(liveProfit, 0, 0, 0); + emit Accrued(liveProfit, 0, 0, 0); vm.expectEmit(true, true, true, true, address(strategy)); emit Reported(reportProfit, 0, 0, 0); @@ -2517,7 +2517,7 @@ contract ProfitLockingTest is Setup { queueHarvestLoss(strategy, reportLoss); vm.expectEmit(true, true, true, true, address(strategy)); - emit Reported(0, liveLoss, 0, 0); + emit Accrued(0, liveLoss, 0, 0); vm.expectEmit(true, true, true, true, address(strategy)); emit Reported(0, reportLoss, 0, 0); @@ -2560,7 +2560,7 @@ contract ProfitLockingTest is Setup { uint256 ppsBeforeReport = strategy.pricePerShare(); vm.expectEmit(true, true, true, true, address(strategy)); - emit Reported(airdrop, 0, 0, 0); + emit Accrued(airdrop, 0, 0, 0); vm.expectEmit(true, true, true, true, address(strategy)); emit Reported(0, 0, 0, 0); From 32b2715df2c039b0015b3629fae643837457a9fc Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Mon, 18 May 2026 16:13:46 -0600 Subject: [PATCH 10/27] fix: block transfers from strategy --- src/TokenizedStrategy.sol | 6 +++++- src/test/ERC20Std.t.sol | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 4e4946e..ff61b96 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -1889,6 +1889,7 @@ contract TokenizedStrategy { * @dev * Requirements: * + * - `from` cannot be the address of the strategy. * - `to` cannot be the zero address. * - `to` cannot be the address of the strategy. * - the caller must have a balance of at least `_amount`. @@ -1972,6 +1973,7 @@ contract TokenizedStrategy { * Requirements: * * - `from` and `to` cannot be the zero address. + * - `from` cannot be the address of the strategy. * - `to` cannot be the address of the strategy. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least @@ -2007,7 +2009,8 @@ contract TokenizedStrategy { * * - `from` cannot be the zero address. * - `to` cannot be the zero address. - * - `to` cannot be the strategies address + * - `from` cannot be the strategies address. + * - `to` cannot be the strategies address. * - `from` must have a balance of at least `amount`. * */ @@ -2019,6 +2022,7 @@ contract TokenizedStrategy { ) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); + require(from != address(this), "ERC20 transfer from strategy"); require(to != address(this), "ERC20 transfer to strategy"); S.balances[from] -= amount; diff --git a/src/test/ERC20Std.t.sol b/src/test/ERC20Std.t.sol index 08ba404..525a7e2 100644 --- a/src/test/ERC20Std.t.sol +++ b/src/test/ERC20Std.t.sol @@ -97,6 +97,15 @@ contract ERC20BaseTest is Setup { } } + function test_transferFromStrategyReverts() public { + address recipient = address(0xBEEF); + uint256 lockedShares = _lockStrategyShares(); + + vm.prank(address(strategy)); + vm.expectRevert("ERC20 transfer from strategy"); + strategy.transfer(recipient, lockedShares); + } + function testFuzz_transferFrom( address recipient_, uint256 approval_, @@ -133,6 +142,21 @@ contract ERC20BaseTest is Setup { } } + function test_transferFromStrategyWithAllowanceReverts() public { + address spender = address(0xCAFE); + address recipient = address(0xBEEF); + uint256 lockedShares = _lockStrategyShares(); + + vm.prank(address(strategy)); + strategy.approve(spender, lockedShares); + + vm.prank(spender); + vm.expectRevert("ERC20 transfer from strategy"); + strategy.transferFrom(address(strategy), recipient, lockedShares); + + assertEq(strategy.allowance(address(strategy), spender), lockedShares); + } + function testFuzz_transferFrom_infiniteApproval( address recipient_, uint256 amount_ @@ -242,6 +266,17 @@ contract ERC20BaseTest is Setup { assertEq(strategy.balanceOf(recipient_), amount_); } + + function _lockStrategyShares() internal returns (uint256 lockedShares) { + mintAndDepositIntoStrategy(strategy, self, 100 ether); + queueHarvestProfit(strategy, 10 ether); + + vm.prank(keeper); + strategy.report(); + + lockedShares = strategy.balanceOf(address(strategy)); + assertGt(lockedShares, 0); + } } contract ERC20PermitTest is Setup { From 5e54a73e595b25bae7fbeadeb3b54e6b8108de96 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Tue, 19 May 2026 12:32:56 -0600 Subject: [PATCH 11/27] fix: commeny --- src/BaseStrategy.sol | 5 ++++- src/TokenizedStrategy.sol | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 8591498..927ebdb 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -141,7 +141,10 @@ abstract contract BaseStrategy { } /// @dev Internal function to initialize the strategy. - function _initialize(address _asset, string memory _name) internal virtual returns (ERC20, ITokenizedStrategy) { + function _initialize( + address _asset, + string memory _name + ) internal virtual returns (ERC20, ITokenizedStrategy) { // Initialize the strategy's storage variables. _delegateCall( abi.encodeCall( diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index ff61b96..8c456c0 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -228,9 +228,15 @@ contract TokenizedStrategy { mapping(address => uint256) nonces; // Mapping of nonces used for permit functions. mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares. mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. + // Last realized total assets. This is used as the accrual baseline during // write flows and to freeze view math during in-flight external callbacks. uint256 lastTotalAssets; + + // Variables for profit reporting and locking. + // We use uint96 for timestamps to fit in the same slot as an address. That overflows in 2.5e+21 years. + // I know Yearn moves slowly but surely V4 will be out by then. + // If the timestamps ever overflow tell the cyborgs still using this code I'm sorry for being cheap. uint256 profitUnlockingRate; // The rate at which locked profit is unlocking. uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock. address keeper; // Address given permission to call {report} and {tend}. @@ -238,8 +244,6 @@ contract TokenizedStrategy { uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. address performanceFeeRecipient; // The address to pay the `performanceFee` to. uint96 lastReport; // The last time a report updated the lock schedule. - uint96 lastAccrual; // The last time accounting synced. - // Access management variables. address management; // Main address that can set all configurable variables. @@ -249,6 +253,8 @@ contract TokenizedStrategy { // Strategy Status uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. bool shutdown; // Bool that can be used to stop deposits into the strategy. + + uint96 lastAccrual; // The last time accounting synced. } /*////////////////////////////////////////////////////////////// From ea64f5fc011454818412e2ddf1da995a9e5acf78 Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Tue, 19 May 2026 14:45:26 -0600 Subject: [PATCH 12/27] feat: tokenized strategy access into library (#115) * refactor: add tokenized strategy library * refactor: import tokenized strategy from base * fix: init order * fix: fail test --- foundry.toml | 1 + src/BaseStrategy.sol | 45 +-- src/libraries/TokenizedStrategyLib.sol | 234 ++++++++++++++++ src/test/AccessControl.t.sol | 69 +++++ src/test/ERC4626Std.t.sol | 43 +++ src/test/TokenizedStrategyLibViews.t.sol | 339 +++++++++++++++++++++++ src/test/mocks/MockFaultyStrategy.sol | 2 +- src/test/mocks/MockStrategy.sol | 201 +++++++++++++- 8 files changed, 902 insertions(+), 32 deletions(-) create mode 100644 src/libraries/TokenizedStrategyLib.sol create mode 100644 src/test/TokenizedStrategyLibViews.t.sol diff --git a/foundry.toml b/foundry.toml index 8e6b883..2ebf4b4 100644 --- a/foundry.toml +++ b/foundry.toml @@ -6,6 +6,7 @@ solc = "0.8.18" evm_version = "paris" optimize = true optimizer_runs = 200 +no_match_test = "testFail" remappings = [ 'forge-std/=lib/forge-std/src/', diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 927ebdb..220dc43 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -3,8 +3,8 @@ pragma solidity >=0.8.18; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -// TokenizedStrategy interface used for internal view delegateCalls. import {ITokenizedStrategy} from "./interfaces/ITokenizedStrategy.sol"; +import {TokenizedStrategyLib as TokenizedStrategy} from "./libraries/TokenizedStrategyLib.sol"; /** * @title YearnV3 Base Strategy @@ -32,8 +32,7 @@ import {ITokenizedStrategy} from "./interfaces/ITokenizedStrategy.sol"; * contains all needed global variables in a manual storage slot. This * means strategists can feel free to implement their own custom storage * variables as they need with no concern of collisions. All global variables - * can be viewed within the Strategy by a simple call using the - * `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();. + * can be viewed within the Strategy using `TokenizedStrategy`. */ abstract contract BaseStrategy { /*////////////////////////////////////////////////////////////// @@ -111,45 +110,33 @@ abstract contract BaseStrategy { */ ERC20 internal immutable asset; - /** - * @dev This variable is set to address(this) during initialization of each strategy. - * - * This can be used to retrieve storage data within the strategy - * contract as if it were a linked library. - * - * i.e. uint256 totalAssets = TokenizedStrategy.totalAssets() - * - * Using address(this) will mean any calls using this variable will lead - * to a call to itself. Which will hit the fallback function and - * delegateCall that to the actual TokenizedStrategy. - */ - ITokenizedStrategy internal immutable TokenizedStrategy; - /** * @notice Used to initialize the strategy on deployment. * - * This will set the `TokenizedStrategy` variable for easy - * internal view calls to the implementation. As well as - * initializing the default storage variables based on the - * parameters and using the deployer for the permissioned roles. + * This will initialize the default storage variables based on the + * parameters and use the deployer for the permissioned roles. * * @param _asset Address of the underlying asset. * @param _name Name the strategy will use. */ constructor(address _asset, string memory _name) { - (asset, TokenizedStrategy) = _initialize(_asset, _name); + asset = ERC20(_asset); + _initialize(_asset, _name, msg.sender, msg.sender, msg.sender); } /// @dev Internal function to initialize the strategy. function _initialize( address _asset, - string memory _name - ) internal virtual returns (ERC20, ITokenizedStrategy) { + string memory _name, + address _management, + address _performanceFeeRecipient, + address _keeper + ) internal virtual { // Initialize the strategy's storage variables. _delegateCall( abi.encodeCall( ITokenizedStrategy.initialize, - (_asset, _name, msg.sender, msg.sender, msg.sender) + (_asset, _name, _management, _performanceFeeRecipient, _keeper) ) ); @@ -163,8 +150,6 @@ abstract contract BaseStrategy { tokenizedStrategyAddress ) } - - return (ERC20(_asset), ITokenizedStrategy(address(this))); } /*////////////////////////////////////////////////////////////// @@ -324,11 +309,11 @@ abstract contract BaseStrategy { * be overridden by strategists. * * This function will be called before any withdraw or redeem to enforce - * any limits desired by the strategist. This can be used for illiquid - * or sandwichable strategies. It should never be lower than `totalIdle`. + * any limits desired by the strategist or integrated protocol. This can + * be used for illiquid or sandwichable strategies. * * EX: - * return TokenIzedStrategy.totalIdle(); + * return asset.balanceOf(address(this)); * * This does not need to take into account the `_owner`'s share balance * or conversion rates from shares to assets. diff --git a/src/libraries/TokenizedStrategyLib.sol b/src/libraries/TokenizedStrategyLib.sol new file mode 100644 index 0000000..beb9b07 --- /dev/null +++ b/src/libraries/TokenizedStrategyLib.sol @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: AGPL-3.0 +pragma solidity >=0.8.18; + +import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +import {ITokenizedStrategy} from "../interfaces/ITokenizedStrategy.sol"; + +library TokenizedStrategyLib { + bytes32 internal constant BASE_STRATEGY_STORAGE = + bytes32(uint256(keccak256("yearn.base.strategy.storage")) - 1); + + // prettier-ignore + struct StrategyData { + ERC20 asset; + uint8 decimals; + string name; + uint256 totalSupply; + mapping(address => uint256) nonces; + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowances; + uint256 lastTotalAssets; + uint256 profitUnlockingRate; + uint96 fullProfitUnlockDate; + address keeper; + uint32 profitMaxUnlockTime; + uint16 performanceFee; + address performanceFeeRecipient; + uint96 lastReport; + address management; + address pendingManagement; + address emergencyAdmin; + uint8 entered; + bool shutdown; + uint96 lastAccrual; + } + + function strategyStorage() internal pure returns (StrategyData storage S) { + bytes32 slot = BASE_STRATEGY_STORAGE; + assembly { + S.slot := slot + } + } + + function asset() internal view returns (address) { + return address(strategyStorage().asset); + } + + function name() internal view returns (string memory) { + return strategyStorage().name; + } + + function symbol() internal view returns (string memory) { + return ITokenizedStrategy(address(this)).symbol(); + } + + function decimals() internal view returns (uint8) { + return strategyStorage().decimals; + } + + function apiVersion() internal view returns (string memory) { + return ITokenizedStrategy(address(this)).apiVersion(); + } + + function MAX_FEE() internal view returns (uint16) { + return ITokenizedStrategy(address(this)).MAX_FEE(); + } + + function FACTORY() internal view returns (address) { + return ITokenizedStrategy(address(this)).FACTORY(); + } + + function management() internal view returns (address) { + return strategyStorage().management; + } + + function pendingManagement() internal view returns (address) { + return strategyStorage().pendingManagement; + } + + function keeper() internal view returns (address) { + return strategyStorage().keeper; + } + + function emergencyAdmin() internal view returns (address) { + return strategyStorage().emergencyAdmin; + } + + function performanceFee() internal view returns (uint16) { + return strategyStorage().performanceFee; + } + + function performanceFeeRecipient() internal view returns (address) { + return strategyStorage().performanceFeeRecipient; + } + + function profitMaxUnlockTime() internal view returns (uint256) { + uint256 _profitMaxUnlockTime = strategyStorage().profitMaxUnlockTime; + if (_profitMaxUnlockTime == type(uint32).max) { + return type(uint256).max; + } + + return _profitMaxUnlockTime; + } + + function lastReport() internal view returns (uint256) { + return uint256(strategyStorage().lastReport); + } + + function lastAccrual() internal view returns (uint256) { + return uint256(strategyStorage().lastAccrual); + } + + function lastTotalAssets() internal view returns (uint256) { + return strategyStorage().lastTotalAssets; + } + + function fullProfitUnlockDate() internal view returns (uint256) { + return uint256(strategyStorage().fullProfitUnlockDate); + } + + function profitUnlockingRate() internal view returns (uint256) { + return strategyStorage().profitUnlockingRate; + } + + function isShutdown() internal view returns (bool) { + return strategyStorage().shutdown; + } + + function totalAssets() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).totalAssets(); + } + + function totalSupply() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).totalSupply(); + } + + function balanceOf(address _account) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).balanceOf(_account); + } + + function allowance( + address _owner, + address _spender + ) internal view returns (uint256) { + return strategyStorage().allowances[_owner][_spender]; + } + + function nonces(address _owner) internal view returns (uint256) { + return strategyStorage().nonces[_owner]; + } + + function DOMAIN_SEPARATOR() internal view returns (bytes32) { + return ITokenizedStrategy(address(this)).DOMAIN_SEPARATOR(); + } + + function unlockedShares() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).unlockedShares(); + } + + function requireManagement(address _sender) internal view { + require(_sender == strategyStorage().management, "!management"); + } + + function requireKeeperOrManagement(address _sender) internal view { + StrategyData storage S = strategyStorage(); + require(_sender == S.keeper || _sender == S.management, "!keeper"); + } + + function requireEmergencyAuthorized(address _sender) internal view { + StrategyData storage S = strategyStorage(); + require( + _sender == S.emergencyAdmin || _sender == S.management, + "!emergency authorized" + ); + } + + function pricePerShare() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).pricePerShare(); + } + + function convertToShares(uint256 _assets) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).convertToShares(_assets); + } + + function convertToAssets(uint256 _shares) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).convertToAssets(_shares); + } + + function previewDeposit(uint256 _assets) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewDeposit(_assets); + } + + function previewMint(uint256 _shares) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewMint(_shares); + } + + function previewWithdraw(uint256 _assets) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewWithdraw(_assets); + } + + function previewRedeem(uint256 _shares) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewRedeem(_shares); + } + + function maxDeposit(address _receiver) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxDeposit(_receiver); + } + + function maxMint(address _receiver) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxMint(_receiver); + } + + function maxWithdraw(address _owner) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxWithdraw(_owner); + } + + function maxWithdraw( + address _owner, + uint256 _maxLoss + ) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxWithdraw(_owner, _maxLoss); + } + + function maxRedeem(address _owner) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxRedeem(_owner); + } + + function maxRedeem( + address _owner, + uint256 _maxLoss + ) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxRedeem(_owner, _maxLoss); + } +} diff --git a/src/test/AccessControl.t.sol b/src/test/AccessControl.t.sol index d6aa107..6f08ef3 100644 --- a/src/test/AccessControl.t.sol +++ b/src/test/AccessControl.t.sol @@ -4,6 +4,52 @@ pragma solidity >=0.8.18; import "forge-std/console.sol"; import {Setup} from "./utils/Setup.sol"; +import {BaseStrategy, ERC20} from "../BaseStrategy.sol"; +import {ITokenizedStrategy} from "../interfaces/ITokenizedStrategy.sol"; + +// Minimal strategy that overrides `_initialize` to demonstrate that role +// addresses passed to `super._initialize` land in the correct storage slots. +// The override uses named arguments, so it only compiles when the parent's +// parameter names align with `ITokenizedStrategy.initialize`. +contract CustomInitMockStrategy is BaseStrategy { + address internal constant CUSTOM_MANAGEMENT = + 0x1111111111111111111111111111111111111111; + address internal constant CUSTOM_FEE_RECIPIENT = + 0x2222222222222222222222222222222222222222; + address internal constant CUSTOM_KEEPER = + 0x3333333333333333333333333333333333333333; + + constructor(address _asset) BaseStrategy(_asset, "Custom Init") {} + + function _initialize( + address _asset, + string memory _name, + address, + address, + address + ) internal override { + super._initialize({ + _asset: _asset, + _name: _name, + _management: CUSTOM_MANAGEMENT, + _performanceFeeRecipient: CUSTOM_FEE_RECIPIENT, + _keeper: CUSTOM_KEEPER + }); + } + + function _deployFunds(uint256) internal override {} + + function _freeFunds(uint256) internal override {} + + function _totalAssets() internal view override returns (uint256) { + return asset.balanceOf(address(this)); + } + + function _harvestAndReport() internal override returns (uint256) { + return _totalAssets(); + } +} + contract AccessControlTest is Setup { function setUp() public override { super.setUp(); @@ -371,6 +417,29 @@ contract AccessControlTest is Setup { strategy.tend(); } + function test_initializeOverride_routesAddressesToCorrectSlots() public { + CustomInitMockStrategy custom = new CustomInitMockStrategy( + address(asset) + ); + ITokenizedStrategy s = ITokenizedStrategy(address(custom)); + + assertEq( + s.management(), + 0x1111111111111111111111111111111111111111, + "!management" + ); + assertEq( + s.performanceFeeRecipient(), + 0x2222222222222222222222222222222222222222, + "!performanceFeeRecipient" + ); + assertEq( + s.keeper(), + 0x3333333333333333333333333333333333333333, + "!keeper" + ); + } + function test_setName(address _address) public { vm.assume(_address != address(strategy) && _address != management); diff --git a/src/test/ERC4626Std.t.sol b/src/test/ERC4626Std.t.sol index 38edd45..b2ac440 100644 --- a/src/test/ERC4626Std.t.sol +++ b/src/test/ERC4626Std.t.sol @@ -34,4 +34,47 @@ contract ERC4626StdTest is ERC4626Test, Setup { if (assets == type(uint256).max) assets -= 1; super.test_deposit(init, assets, allowance); } + + // The pinned ERC4626 test suite still uses legacy `testFail_*` names for + // these cases. Newer Forge versions reject those, so we filter them out in + // foundry.toml and keep the same coverage here with explicit expectRevert. + function test_erc4626WithdrawWithoutAllowanceReverts( + Init memory init, + uint256 assets + ) public { + setUpVault(init); + address caller = init.user[0]; + address receiver = init.user[1]; + address owner = init.user[2]; + assets = bound(assets, 0, _max_withdraw(owner)); + + vm.assume(caller != owner); + vm.assume(assets > 0); + + _approve(_vault_, owner, caller, 0); + + vm.expectRevert(); + vm.prank(caller); + strategy.withdraw(assets, receiver, owner); + } + + function test_erc4626RedeemWithoutAllowanceReverts( + Init memory init, + uint256 shares + ) public { + setUpVault(init); + address caller = init.user[0]; + address receiver = init.user[1]; + address owner = init.user[2]; + shares = bound(shares, 0, _max_redeem(owner)); + + vm.assume(caller != owner); + vm.assume(shares > 0); + + _approve(_vault_, owner, caller, 0); + + vm.expectRevert(); + vm.prank(caller); + strategy.redeem(shares, receiver, owner); + } } diff --git a/src/test/TokenizedStrategyLibViews.t.sol b/src/test/TokenizedStrategyLibViews.t.sol new file mode 100644 index 0000000..c4e0965 --- /dev/null +++ b/src/test/TokenizedStrategyLibViews.t.sol @@ -0,0 +1,339 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity >=0.8.18; + +import {Setup} from "./utils/Setup.sol"; +import {MockStrategy} from "./mocks/MockStrategy.sol"; + +contract TokenizedStrategyLibViewsTest is Setup { + bytes32 internal constant PERMIT_TYPEHASH = + keccak256( + "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" + ); + + MockStrategy internal libraryStrategy; + + function setUp() public override { + super.setUp(); + libraryStrategy = MockStrategy(address(strategy)); + } + + function test_tokenizedStrategyLibraryViewsMatchDirectCalls() public { + uint256 ownerSk = 0xA11CE; + address owner = vm.addr(ownerSk); + address spender = address(0xBEEF); + address pendingManagement = address(0xCAFE); + address newKeeper = address(0xD00D); + address newEmergencyAdmin = address(0xEAA); + address newPerformanceFeeRecipient = address(0xFEE); + uint256 amount = 100_000 * wad; + + _assertAllViewsMatch(owner, spender, amount / 10, amount / 20, 77); + + setFees(0, 1_250); + mintAndDepositIntoStrategy(strategy, owner, amount); + + vm.prank(owner); + strategy.approve(spender, amount / 3); + + _permit(owner, spender, amount / 7, 1 days, ownerSk); + + vm.prank(management); + strategy.setPendingManagement(pendingManagement); + + vm.prank(management); + strategy.setPerformanceFeeRecipient(newPerformanceFeeRecipient); + + vm.prank(management); + strategy.setProfitMaxUnlockTime(14 days); + + skip(1); + createAndCheckProfit(strategy, amount / 5, 0, amount / 40); + + vm.prank(management); + strategy.setKeeper(newKeeper); + + vm.prank(management); + strategy.setEmergencyAdmin(newEmergencyAdmin); + + skip(3 days); + _assertAllViewsMatch(owner, spender, amount / 11, amount / 13, 123); + _assertAccountViewsMatch(address(strategy), spender); + _assertAccountViewsMatch(newPerformanceFeeRecipient, spender); + + vm.prank(newEmergencyAdmin); + strategy.shutdownStrategy(); + + _assertAllViewsMatch(owner, spender, amount / 17, amount / 19, MAX_BPS); + _assertAuthHelpersMatch(newKeeper, newEmergencyAdmin); + } + + function _assertAllViewsMatch( + address owner, + address spender, + uint256 assets, + uint256 shares, + uint256 maxLoss + ) internal { + assertEq(libraryStrategy.libraryAsset(), strategy.asset(), "asset"); + assertEq( + keccak256(bytes(libraryStrategy.libraryName())), + keccak256(bytes(strategy.name())), + "name" + ); + assertEq( + keccak256(bytes(libraryStrategy.librarySymbol())), + keccak256(bytes(strategy.symbol())), + "symbol" + ); + assertEq( + libraryStrategy.libraryDecimals(), + strategy.decimals(), + "decimals" + ); + assertEq( + keccak256(bytes(libraryStrategy.libraryApiVersion())), + keccak256(bytes(strategy.apiVersion())), + "apiVersion" + ); + assertEq( + libraryStrategy.libraryMAX_FEE(), + strategy.MAX_FEE(), + "MAX_FEE" + ); + assertEq( + libraryStrategy.libraryFACTORY(), + strategy.FACTORY(), + "FACTORY" + ); + assertEq( + libraryStrategy.libraryManagement(), + strategy.management(), + "management" + ); + assertEq( + libraryStrategy.libraryPendingManagement(), + strategy.pendingManagement(), + "pendingManagement" + ); + assertEq(libraryStrategy.libraryKeeper(), strategy.keeper(), "keeper"); + assertEq( + libraryStrategy.libraryEmergencyAdmin(), + strategy.emergencyAdmin(), + "emergencyAdmin" + ); + assertEq( + libraryStrategy.libraryPerformanceFee(), + strategy.performanceFee(), + "performanceFee" + ); + assertEq( + libraryStrategy.libraryPerformanceFeeRecipient(), + strategy.performanceFeeRecipient(), + "performanceFeeRecipient" + ); + assertEq( + libraryStrategy.libraryProfitMaxUnlockTime(), + strategy.profitMaxUnlockTime(), + "profitMaxUnlockTime" + ); + assertEq( + libraryStrategy.libraryLastReport(), + strategy.lastReport(), + "lastReport" + ); + assertEq( + libraryStrategy.libraryLastAccrual(), + strategy.lastAccrual(), + "lastAccrual" + ); + assertEq( + libraryStrategy.libraryLastTotalAssets(), + strategy.lastTotalAssets(), + "lastTotalAssets" + ); + assertEq( + libraryStrategy.libraryFullProfitUnlockDate(), + strategy.fullProfitUnlockDate(), + "fullProfitUnlockDate" + ); + assertEq( + libraryStrategy.libraryProfitUnlockingRate(), + strategy.profitUnlockingRate(), + "profitUnlockingRate" + ); + assertEq( + libraryStrategy.libraryIsShutdown(), + strategy.isShutdown(), + "isShutdown" + ); + assertEq( + libraryStrategy.libraryTotalAssets(), + strategy.totalAssets(), + "totalAssets" + ); + assertEq( + libraryStrategy.libraryTotalSupply(), + strategy.totalSupply(), + "totalSupply" + ); + assertEq( + libraryStrategy.libraryDOMAIN_SEPARATOR(), + strategy.DOMAIN_SEPARATOR(), + "DOMAIN_SEPARATOR" + ); + assertEq( + libraryStrategy.libraryUnlockedShares(), + strategy.unlockedShares(), + "unlockedShares" + ); + assertEq( + libraryStrategy.libraryPricePerShare(), + strategy.pricePerShare(), + "pricePerShare" + ); + assertEq( + libraryStrategy.libraryConvertToShares(assets), + strategy.convertToShares(assets), + "convertToShares" + ); + assertEq( + libraryStrategy.libraryConvertToAssets(shares), + strategy.convertToAssets(shares), + "convertToAssets" + ); + assertEq( + libraryStrategy.libraryPreviewDeposit(assets), + strategy.previewDeposit(assets), + "previewDeposit" + ); + assertEq( + libraryStrategy.libraryPreviewMint(shares), + strategy.previewMint(shares), + "previewMint" + ); + assertEq( + libraryStrategy.libraryPreviewWithdraw(assets), + strategy.previewWithdraw(assets), + "previewWithdraw" + ); + assertEq( + libraryStrategy.libraryPreviewRedeem(shares), + strategy.previewRedeem(shares), + "previewRedeem" + ); + assertEq( + libraryStrategy.libraryMaxDeposit(owner), + strategy.maxDeposit(owner), + "maxDeposit" + ); + assertEq( + libraryStrategy.libraryMaxMint(owner), + strategy.maxMint(owner), + "maxMint" + ); + assertEq( + libraryStrategy.libraryMaxWithdraw(owner), + strategy.maxWithdraw(owner), + "maxWithdraw" + ); + assertEq( + libraryStrategy.libraryMaxWithdraw(owner, maxLoss), + strategy.maxWithdraw(owner, maxLoss), + "maxWithdraw maxLoss" + ); + assertEq( + libraryStrategy.libraryMaxRedeem(owner), + strategy.maxRedeem(owner), + "maxRedeem" + ); + assertEq( + libraryStrategy.libraryMaxRedeem(owner, maxLoss), + strategy.maxRedeem(owner, maxLoss), + "maxRedeem maxLoss" + ); + + _assertAccountViewsMatch(owner, spender); + } + + function _assertAccountViewsMatch(address owner, address spender) internal { + assertEq( + libraryStrategy.libraryBalanceOf(owner), + strategy.balanceOf(owner), + "balanceOf" + ); + assertEq( + libraryStrategy.libraryAllowance(owner, spender), + strategy.allowance(owner, spender), + "allowance" + ); + assertEq( + libraryStrategy.libraryNonces(owner), + strategy.nonces(owner), + "nonces" + ); + } + + function _assertAuthHelpersMatch( + address currentKeeper, + address currentEmergencyAdmin + ) internal { + strategy.requireManagement(management); + libraryStrategy.libraryRequireManagement(management); + + strategy.requireKeeperOrManagement(management); + strategy.requireKeeperOrManagement(currentKeeper); + libraryStrategy.libraryRequireKeeperOrManagement(management); + libraryStrategy.libraryRequireKeeperOrManagement(currentKeeper); + + strategy.requireEmergencyAuthorized(management); + strategy.requireEmergencyAuthorized(currentEmergencyAdmin); + libraryStrategy.libraryRequireEmergencyAuthorized(management); + libraryStrategy.libraryRequireEmergencyAuthorized( + currentEmergencyAdmin + ); + + vm.expectRevert("!management"); + strategy.requireManagement(address(0xBAD)); + vm.expectRevert("!management"); + libraryStrategy.libraryRequireManagement(address(0xBAD)); + + vm.expectRevert("!keeper"); + strategy.requireKeeperOrManagement(address(0xBAD)); + vm.expectRevert("!keeper"); + libraryStrategy.libraryRequireKeeperOrManagement(address(0xBAD)); + + vm.expectRevert("!emergency authorized"); + strategy.requireEmergencyAuthorized(address(0xBAD)); + vm.expectRevert("!emergency authorized"); + libraryStrategy.libraryRequireEmergencyAuthorized(address(0xBAD)); + } + + function _permit( + address owner, + address spender, + uint256 amount, + uint256 deadline, + uint256 ownerSk + ) internal { + bytes32 structHash = keccak256( + abi.encode( + PERMIT_TYPEHASH, + owner, + spender, + amount, + strategy.nonces(owner), + deadline + ) + ); + bytes32 digest = keccak256( + abi.encodePacked( + "\x19\x01", + strategy.DOMAIN_SEPARATOR(), + structHash + ) + ); + (uint8 v, bytes32 r, bytes32 s) = vm.sign(ownerSk, digest); + + strategy.permit(owner, spender, amount, deadline, v, r, s); + } +} diff --git a/src/test/mocks/MockFaultyStrategy.sol b/src/test/mocks/MockFaultyStrategy.sol index 412c9da..a17f7f6 100644 --- a/src/test/mocks/MockFaultyStrategy.sol +++ b/src/test/mocks/MockFaultyStrategy.sol @@ -2,7 +2,7 @@ pragma solidity >=0.8.18; import {MockYieldSource} from "./MockYieldSource.sol"; -import {BaseStrategy, ERC20} from "../../BaseStrategy.sol"; +import {BaseStrategy, ERC20, TokenizedStrategy} from "../../BaseStrategy.sol"; interface IPappa { function callBack( diff --git a/src/test/mocks/MockStrategy.sol b/src/test/mocks/MockStrategy.sol index f4015c8..807cf1a 100644 --- a/src/test/mocks/MockStrategy.sol +++ b/src/test/mocks/MockStrategy.sol @@ -2,7 +2,7 @@ pragma solidity >=0.8.18; import {MockYieldSource} from "./MockYieldSource.sol"; -import {BaseStrategy, ERC20} from "../../BaseStrategy.sol"; +import {BaseStrategy, ERC20, TokenizedStrategy} from "../../BaseStrategy.sol"; contract MockStrategy is BaseStrategy { address public yieldSource; @@ -77,4 +77,203 @@ contract MockStrategy is BaseStrategy { function onlyLetEmergencyAdminsIn() public onlyEmergencyAuthorized { emergentizated = true; } + + function libraryAsset() external view returns (address) { + return TokenizedStrategy.asset(); + } + + function libraryName() external view returns (string memory) { + return TokenizedStrategy.name(); + } + + function librarySymbol() external view returns (string memory) { + return TokenizedStrategy.symbol(); + } + + function libraryDecimals() external view returns (uint8) { + return TokenizedStrategy.decimals(); + } + + function libraryApiVersion() external view returns (string memory) { + return TokenizedStrategy.apiVersion(); + } + + function libraryMAX_FEE() external view returns (uint16) { + return TokenizedStrategy.MAX_FEE(); + } + + function libraryFACTORY() external view returns (address) { + return TokenizedStrategy.FACTORY(); + } + + function libraryManagement() external view returns (address) { + return TokenizedStrategy.management(); + } + + function libraryPendingManagement() external view returns (address) { + return TokenizedStrategy.pendingManagement(); + } + + function libraryKeeper() external view returns (address) { + return TokenizedStrategy.keeper(); + } + + function libraryEmergencyAdmin() external view returns (address) { + return TokenizedStrategy.emergencyAdmin(); + } + + function libraryPerformanceFee() external view returns (uint16) { + return TokenizedStrategy.performanceFee(); + } + + function libraryPerformanceFeeRecipient() external view returns (address) { + return TokenizedStrategy.performanceFeeRecipient(); + } + + function libraryProfitMaxUnlockTime() external view returns (uint256) { + return TokenizedStrategy.profitMaxUnlockTime(); + } + + function libraryLastReport() external view returns (uint256) { + return TokenizedStrategy.lastReport(); + } + + function libraryLastAccrual() external view returns (uint256) { + return TokenizedStrategy.lastAccrual(); + } + + function libraryLastTotalAssets() external view returns (uint256) { + return TokenizedStrategy.lastTotalAssets(); + } + + function libraryFullProfitUnlockDate() external view returns (uint256) { + return TokenizedStrategy.fullProfitUnlockDate(); + } + + function libraryProfitUnlockingRate() external view returns (uint256) { + return TokenizedStrategy.profitUnlockingRate(); + } + + function libraryIsShutdown() external view returns (bool) { + return TokenizedStrategy.isShutdown(); + } + + function libraryTotalAssets() external view returns (uint256) { + return TokenizedStrategy.totalAssets(); + } + + function libraryTotalSupply() external view returns (uint256) { + return TokenizedStrategy.totalSupply(); + } + + function libraryBalanceOf( + address _account + ) external view returns (uint256) { + return TokenizedStrategy.balanceOf(_account); + } + + function libraryAllowance( + address _owner, + address _spender + ) external view returns (uint256) { + return TokenizedStrategy.allowance(_owner, _spender); + } + + function libraryNonces(address _owner) external view returns (uint256) { + return TokenizedStrategy.nonces(_owner); + } + + function libraryDOMAIN_SEPARATOR() external view returns (bytes32) { + return TokenizedStrategy.DOMAIN_SEPARATOR(); + } + + function libraryUnlockedShares() external view returns (uint256) { + return TokenizedStrategy.unlockedShares(); + } + + function libraryPricePerShare() external view returns (uint256) { + return TokenizedStrategy.pricePerShare(); + } + + function libraryConvertToShares( + uint256 _assets + ) external view returns (uint256) { + return TokenizedStrategy.convertToShares(_assets); + } + + function libraryConvertToAssets( + uint256 _shares + ) external view returns (uint256) { + return TokenizedStrategy.convertToAssets(_shares); + } + + function libraryPreviewDeposit( + uint256 _assets + ) external view returns (uint256) { + return TokenizedStrategy.previewDeposit(_assets); + } + + function libraryPreviewMint( + uint256 _shares + ) external view returns (uint256) { + return TokenizedStrategy.previewMint(_shares); + } + + function libraryPreviewWithdraw( + uint256 _assets + ) external view returns (uint256) { + return TokenizedStrategy.previewWithdraw(_assets); + } + + function libraryPreviewRedeem( + uint256 _shares + ) external view returns (uint256) { + return TokenizedStrategy.previewRedeem(_shares); + } + + function libraryMaxDeposit( + address _receiver + ) external view returns (uint256) { + return TokenizedStrategy.maxDeposit(_receiver); + } + + function libraryMaxMint(address _receiver) external view returns (uint256) { + return TokenizedStrategy.maxMint(_receiver); + } + + function libraryMaxWithdraw( + address _owner + ) external view returns (uint256) { + return TokenizedStrategy.maxWithdraw(_owner); + } + + function libraryMaxWithdraw( + address _owner, + uint256 _maxLoss + ) external view returns (uint256) { + return TokenizedStrategy.maxWithdraw(_owner, _maxLoss); + } + + function libraryMaxRedeem(address _owner) external view returns (uint256) { + return TokenizedStrategy.maxRedeem(_owner); + } + + function libraryMaxRedeem( + address _owner, + uint256 _maxLoss + ) external view returns (uint256) { + return TokenizedStrategy.maxRedeem(_owner, _maxLoss); + } + + function libraryRequireManagement(address _sender) external view { + TokenizedStrategy.requireManagement(_sender); + } + + function libraryRequireKeeperOrManagement(address _sender) external view { + TokenizedStrategy.requireKeeperOrManagement(_sender); + } + + function libraryRequireEmergencyAuthorized(address _sender) external view { + TokenizedStrategy.requireEmergencyAuthorized(_sender); + } } From 3781f5e336ff690af62ae43f3a627a6da176887d Mon Sep 17 00:00:00 2001 From: murderteeth <89237203+murderteeth@users.noreply.github.com> Date: Tue, 19 May 2026 16:49:23 -0400 Subject: [PATCH 13/27] Supply-chain hardening sweep (#113) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1 PM config(s); pin 5 deps; pin 7 actions 🛡️ Automated Co-authored-by: Schlag <89420541+Schlagonia@users.noreply.github.com> --- .github/workflows/lint.yaml | 10 +++++----- .github/workflows/test.yaml | 4 ++-- .yarnrc.yml | 3 +++ package.json | 15 ++++++++------- yarn.lock | 10 +++++----- 5 files changed, 23 insertions(+), 19 deletions(-) create mode 100644 .yarnrc.yml diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 772b097..901c5d2 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -13,12 +13,12 @@ jobs: steps: - name: Check out github repository - uses: actions/checkout@v2 + uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 with: fetch-depth: 1 - name: Setup node.js - uses: actions/setup-node@v1 + uses: actions/setup-node@f1f314fca9dfce2769ece7d933488f076716723e # v1 with: node-version: '16.x' @@ -27,7 +27,7 @@ jobs: run: echo "::set-output name=dir::$(yarn cache dir)" - name: Restore yarn cache - uses: actions/cache@v2 + uses: actions/cache@8492260343ad570701412c2f464a5877dc76bace # v2 id: yarn-cache with: path: | @@ -50,9 +50,9 @@ jobs: steps: - name: Check out github repository - uses: actions/checkout@v2 + uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 with: fetch-depth: 0 - name: Run commitlint - uses: wagoid/commitlint-github-action@v2 \ No newline at end of file + uses: wagoid/commitlint-github-action@4b1bcb1c72f99fbd6aa6b34cc3fb59200f01f993 # v2 \ No newline at end of file diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 27cd735..db894bc 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -18,12 +18,12 @@ jobs: name: Foundry project runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 with: submodules: recursive - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 + uses: foundry-rs/foundry-toolchain@c7450ba673e133f5ee30098b3b54f444d3a2ca2d # v1 with: version: nightly diff --git a/.yarnrc.yml b/.yarnrc.yml new file mode 100644 index 0000000..dd78e98 --- /dev/null +++ b/.yarnrc.yml @@ -0,0 +1,3 @@ +npmMinimalAgeGate: 10080 +enableScripts: false +defaultSemverRangePrefix: "" diff --git a/package.json b/package.json index 5ed2f4f..d7e5dd9 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,18 @@ { "name": "yearn_base_strategy", "devDependencies": { - "prettier": "^2.5.1", - "prettier-plugin-solidity": "^1.0.0-beta.19", - "pretty-quick": "^3.1.3", + "prettier": "2.8.4", + "prettier-plugin-solidity": "1.1.3", + "pretty-quick": "3.1.3", "solc": "0.8.18", - "solhint": "^3.3.7", - "solhint-plugin-prettier": "^0.0.5" + "solhint": "3.4.0", + "solhint-plugin-prettier": "0.0.5" }, "scripts": { "format": "prettier --write 'src/**/*.(sol|json)' 'script/*.sol'", "format:check": "prettier --check 'src/**/*.*(sol|json)' 'script/*.sol'", "lint": "solhint 'src/**/*.sol' 'script/*.sol'", "lint:fix": "solhint --fix 'src/**/*.sol' 'script/*.sol'" - } - } \ No newline at end of file + }, + "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e" +} diff --git a/yarn.lock b/yarn.lock index e80cbe0..65704d5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -580,7 +580,7 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier-plugin-solidity@^1.0.0-alpha.14, prettier-plugin-solidity@^1.0.0-beta.19: +prettier-plugin-solidity@1.1.3: version "1.1.3" resolved "https://registry.npmjs.org/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.3.tgz" integrity sha512-fQ9yucPi2sBbA2U2Xjh6m4isUTJ7S7QLc/XDDsktqqxYfTwdYKJ0EnnywXHwCGAaYbQNK+HIYPL1OemxuMsgeg== @@ -589,12 +589,12 @@ prettier-plugin-solidity@^1.0.0-alpha.14, prettier-plugin-solidity@^1.0.0-beta.1 semver "^7.3.8" solidity-comments-extractor "^0.0.7" -"prettier@^1.15.0 || ^2.0.0", prettier@^2.5.1, prettier@^2.8.3, prettier@>=2.0.0, "prettier@>=2.3.0 || >=3.0.0-alpha.0": +prettier@2.8.4, prettier@^2.8.3: version "2.8.4" resolved "https://registry.npmjs.org/prettier/-/prettier-2.8.4.tgz" integrity sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw== -pretty-quick@^3.1.3: +pretty-quick@3.1.3: version "3.1.3" resolved "https://registry.npmjs.org/pretty-quick/-/pretty-quick-3.1.3.tgz" integrity sha512-kOCi2FJabvuh1as9enxYmrnBC6tVMoVOenMaBqRfsvBHB0cbpYHjdQEpSglpASDFEXVwplpcGR4CLEaisYAFcA== @@ -685,14 +685,14 @@ solc@0.8.18: semver "^5.5.0" tmp "0.0.33" -solhint-plugin-prettier@^0.0.5: +solhint-plugin-prettier@0.0.5: version "0.0.5" resolved "https://registry.npmjs.org/solhint-plugin-prettier/-/solhint-plugin-prettier-0.0.5.tgz" integrity sha512-7jmWcnVshIrO2FFinIvDQmhQpfpS2rRRn3RejiYgnjIE68xO2bvrYvjqVNfrio4xH9ghOqn83tKuTzLjEbmGIA== dependencies: prettier-linter-helpers "^1.0.0" -solhint@^3.3.7: +solhint@3.4.0: version "3.4.0" resolved "https://registry.npmjs.org/solhint/-/solhint-3.4.0.tgz" integrity sha512-FYEs/LoTxMsWFP/OGsEqR1CBDn3Bn7hrTWsgtjai17MzxITgearIdlo374KKZjjIycu8E2xBcJ+RSWeoBvQmkw== From 1e5b2dd7e76d5a7de5e281bf945b8f66c2a0ad93 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Tue, 19 May 2026 14:53:13 -0600 Subject: [PATCH 14/27] chore: bump api version to 3.1.0 --- src/TokenizedStrategy.sol | 2 +- src/test/ERC20Std.t.sol | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 8c456c0..9ff7486 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -354,7 +354,7 @@ contract TokenizedStrategy { //////////////////////////////////////////////////////////////*/ /// @notice API version this TokenizedStrategy implements. - string internal constant API_VERSION = "3.0.4"; + string internal constant API_VERSION = "3.1.0"; /// @notice Value to set the `entered` flag to during a call. uint8 internal constant ENTERED = 2; diff --git a/src/test/ERC20Std.t.sol b/src/test/ERC20Std.t.sol index 525a7e2..99b10fa 100644 --- a/src/test/ERC20Std.t.sol +++ b/src/test/ERC20Std.t.sol @@ -23,7 +23,7 @@ contract ERC20BaseTest is Setup { string(abi.encodePacked("ys", asset.symbol())) ); assertEq(strategy.decimals(), 18); - assertEq(strategy.apiVersion(), "3.0.4"); + assertEq(strategy.apiVersion(), "3.1.0"); } function testFuzz_mint(address account_, uint256 amount_) public { From a9720676e74b760d6f54ed37ead5c6b0dc038a80 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Tue, 19 May 2026 15:33:52 -0600 Subject: [PATCH 15/27] fix: accrue before updating profit unlock time --- src/TokenizedStrategy.sol | 2 ++ src/test/Accounting.t.sol | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 9ff7486..0a17a2d 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -1814,6 +1814,8 @@ contract TokenizedStrategy { uint256 _profitMaxUnlockTime ) external onlyManagement { StrategyData storage S = _strategyStorage(); + _accrue(S); + uint32 newProfitMaxUnlockTime = _profitMaxUnlockTime > type(uint32).max ? type(uint32).max : uint32(_profitMaxUnlockTime); diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index afd1406..cfc2561 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -248,6 +248,48 @@ contract AccountingTest is Setup { ); } + function test_settingProfitMaxUnlockTimeSyncsExistingProfit( + address _user, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != keeper && + _user != management && + _user != emergencyAdmin && + _user != protocolFeeRecipient && + _user != performanceFeeRecipient && + _user != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _user, _amount); + + uint256 profit = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), profit); + + skip(1); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit Accrued(profit, 0, 0, 0); + + vm.prank(management); + strategy.setProfitMaxUnlockTime(0); + + assertEq(strategy.profitMaxUnlockTime(), 0, "!unlock time"); + assertEq(strategy.lastTotalAssets(), _amount + profit, "!synced"); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + } + function test_lossHitsViewsImmediately( address _user, uint256 _amount, From bfe27178ff4cefa171ca00834233d0fb25201a1c Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Tue, 19 May 2026 15:37:59 -0600 Subject: [PATCH 16/27] fix: expose strategy total assets view --- src/BaseStrategy.sol | 4 ---- src/test/AccessControl.t.sol | 20 ++++++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 220dc43..ff89583 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -375,15 +375,11 @@ abstract contract BaseStrategy { /** * @notice Returns the strategies best current estimate for total assets. * @dev Read-only callback for the TokenizedStrategy. - * - * This can only be called by this strategy during a delegate call flow so - * msg.sender must equal address(this). */ function strategyTotalAssets() external view virtual - onlySelf returns (uint256) { return _totalAssets(); diff --git a/src/test/AccessControl.t.sol b/src/test/AccessControl.t.sol index 6f08ef3..33646db 100644 --- a/src/test/AccessControl.t.sol +++ b/src/test/AccessControl.t.sol @@ -356,6 +356,26 @@ contract AccessControlTest is Setup { assertEq(asset.balanceOf(address(strategy)), _amount, "!out"); } + function test_accessControl_strategyTotalAssets( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume(_address != address(0) && _address != address(strategy)); + + // deposit into the vault and should deploy funds + mintAndDepositIntoStrategy(strategy, user, _amount); + asset.mint(address(strategy), _amount); + + // works from random address + vm.prank(_address); + assertEq(strategy.strategyTotalAssets(), _amount * 2, "!random"); + + // works from management + vm.prank(management); + assertEq(strategy.strategyTotalAssets(), _amount * 2, "!management"); + } + function test_accessControl_harvestAndReport( address _address, uint256 _amount From be2cdb13a19063371974bcd8a74110c1a799211c Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Tue, 19 May 2026 16:27:19 -0600 Subject: [PATCH 17/27] chore: pack struct --- src/BaseStrategy.sol | 7 +------ src/TokenizedStrategy.sol | 8 ++++---- src/libraries/TokenizedStrategyLib.sol | 2 +- src/test/mocks/MockStorage.sol | 6 +++--- 4 files changed, 9 insertions(+), 14 deletions(-) diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index ff89583..7b3244c 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -376,12 +376,7 @@ abstract contract BaseStrategy { * @notice Returns the strategies best current estimate for total assets. * @dev Read-only callback for the TokenizedStrategy. */ - function strategyTotalAssets() - external - view - virtual - returns (uint256) - { + function strategyTotalAssets() external view virtual returns (uint256) { return _totalAssets(); } diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 0a17a2d..5fa39c0 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -254,7 +254,7 @@ contract TokenizedStrategy { uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. bool shutdown; // Bool that can be used to stop deposits into the strategy. - uint96 lastAccrual; // The last time accounting synced. + uint80 lastAccrual; // The last time accounting synced. } /*////////////////////////////////////////////////////////////// @@ -474,7 +474,7 @@ contract TokenizedStrategy { // Initialize both timestamps to the deployment block. S.lastReport = uint96(block.timestamp); // -1 to not allow first deposit inflation - S.lastAccrual = uint96(block.timestamp - 1); + S.lastAccrual = uint80(block.timestamp - 1); // Set the default management address. Can't be 0. require(_management != address(0), "ZERO ADDRESS"); @@ -843,7 +843,7 @@ contract TokenizedStrategy { /// @dev Internal implementation of {totalSupply}. /// @notice We don't increase totalSupply until actual shares are minted. - /// This can cause disconnection between conversions done manually + /// This can cause disconnection between conversions done manually. function _totalSupply( StrategyData storage S ) internal view returns (uint256) { @@ -1181,7 +1181,7 @@ contract TokenizedStrategy { } S.lastTotalAssets = newTotalAssets; - S.lastAccrual = uint96(block.timestamp); + S.lastAccrual = uint80(block.timestamp); emit Accrued(profit, loss, protocolFees, totalFees - protocolFees); } diff --git a/src/libraries/TokenizedStrategyLib.sol b/src/libraries/TokenizedStrategyLib.sol index beb9b07..fba706b 100644 --- a/src/libraries/TokenizedStrategyLib.sol +++ b/src/libraries/TokenizedStrategyLib.sol @@ -31,7 +31,7 @@ library TokenizedStrategyLib { address emergencyAdmin; uint8 entered; bool shutdown; - uint96 lastAccrual; + uint80 lastAccrual; } function strategyStorage() internal pure returns (StrategyData storage S) { diff --git a/src/test/mocks/MockStorage.sol b/src/test/mocks/MockStorage.sol index 97d681a..ab4351a 100644 --- a/src/test/mocks/MockStorage.sol +++ b/src/test/mocks/MockStorage.sol @@ -34,7 +34,6 @@ contract MockStorage { uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. address performanceFeeRecipient; // The address to pay the `performanceFee` to. uint96 lastReport; // The last time a report updated the lock schedule. - uint96 lastAccrual; // The last time accounting synced. // Access management variables. @@ -44,6 +43,7 @@ contract MockStorage { // Strategy status checks. - bool entered; // Bool to prevent reentrancy. - bool shutdown; // Bool that can be used to stop deposits into the strategy. + uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. + bool shutdown; // Bool that can be used to stop deposits into the strategy. + uint80 lastAccrual; // The last time accounting synced. } From ce50b28faea74e7b3301f88e0368985fa43c4206 Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Sun, 24 May 2026 10:53:02 -0600 Subject: [PATCH 18/27] feat: add strategy pause control (#116) --- src/TokenizedStrategy.sol | 78 +++++- src/interfaces/IEvents.sol | 5 + src/interfaces/ITokenizedStrategy.sol | 6 + src/libraries/TokenizedStrategyLib.sol | 7 +- src/test/Pause.t.sol | 336 +++++++++++++++++++++++ src/test/Shutdown.t.sol | 2 +- src/test/TokenizedStrategyLibViews.t.sol | 5 + src/test/mocks/MockStorage.sol | 3 +- src/test/mocks/MockStrategy.sol | 4 + 9 files changed, 429 insertions(+), 17 deletions(-) create mode 100644 src/test/Pause.t.sol diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 5fa39c0..a9ce9a0 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -83,6 +83,11 @@ contract TokenizedStrategy { */ event StrategyShutdown(); + /** + * @notice Emitted when a strategies paused status is updated. + */ + event UpdatePaused(bool paused); + /** * @notice Emitted on the initialization of any new `strategy` that uses `asset` * with this specific `apiVersion`. @@ -253,8 +258,9 @@ contract TokenizedStrategy { // Strategy Status uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. bool shutdown; // Bool that can be used to stop deposits into the strategy. + bool paused; // Bool that can be used to stop user facing 4626 functions. - uint80 lastAccrual; // The last time accounting synced. + uint72 lastAccrual; // The last time accounting synced. } /*////////////////////////////////////////////////////////////// @@ -305,6 +311,14 @@ contract TokenizedStrategy { S.entered = NOT_ENTERED; } + /** + * @dev Require that the strategy is not paused. + */ + modifier whenNotPaused() { + require(!_strategyStorage().paused, "paused"); + _; + } + /** * @notice Require a caller is `management`. * @dev Is left public so that it can be used by the Strategy. @@ -474,7 +488,7 @@ contract TokenizedStrategy { // Initialize both timestamps to the deployment block. S.lastReport = uint96(block.timestamp); // -1 to not allow first deposit inflation - S.lastAccrual = uint80(block.timestamp - 1); + S.lastAccrual = uint72(block.timestamp - 1); // Set the default management address. Can't be 0. require(_management != address(0), "ZERO ADDRESS"); @@ -500,7 +514,7 @@ contract TokenizedStrategy { function deposit( uint256 assets, address receiver - ) external nonReentrant returns (uint256 shares) { + ) external whenNotPaused nonReentrant returns (uint256 shares) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); _accrue(S); @@ -534,7 +548,7 @@ contract TokenizedStrategy { function mint( uint256 shares, address receiver - ) external nonReentrant returns (uint256 assets) { + ) external whenNotPaused nonReentrant returns (uint256 assets) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); _accrue(S); @@ -582,7 +596,7 @@ contract TokenizedStrategy { address receiver, address owner, uint256 maxLoss - ) public nonReentrant returns (uint256 shares) { + ) public whenNotPaused nonReentrant returns (uint256 shares) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); _accrue(S); @@ -634,7 +648,7 @@ contract TokenizedStrategy { address receiver, address owner, uint256 maxLoss - ) public nonReentrant returns (uint256) { + ) public whenNotPaused nonReentrant returns (uint256) { // Get the storage slot for all following calls. StrategyData storage S = _strategyStorage(); _accrue(S); @@ -961,8 +975,8 @@ contract TokenizedStrategy { StrategyData storage S, address receiver ) internal view returns (uint256) { - // Cannot deposit when shutdown or to the strategy. - if (S.shutdown || receiver == address(this)) return 0; + // Cannot deposit when shutdown, paused or to the strategy. + if (S.shutdown || S.paused || receiver == address(this)) return 0; return IBaseStrategy(address(this)).availableDepositLimit(receiver); } @@ -972,8 +986,8 @@ contract TokenizedStrategy { StrategyData storage S, address receiver ) internal view returns (uint256 maxMint_) { - // Cannot mint when shutdown or to the strategy. - if (S.shutdown || receiver == address(this)) return 0; + // Cannot mint when shutdown, paused or to the strategy. + if (S.shutdown || S.paused || receiver == address(this)) return 0; maxMint_ = IBaseStrategy(address(this)).availableDepositLimit(receiver); if (maxMint_ != type(uint256).max) { @@ -986,6 +1000,9 @@ contract TokenizedStrategy { StrategyData storage S, address owner ) internal view returns (uint256 maxWithdraw_) { + // Cannot withdraw when paused. + if (S.paused) return 0; + // Get the max the owner could withdraw currently. maxWithdraw_ = IBaseStrategy(address(this)).availableWithdrawLimit( owner @@ -1012,6 +1029,9 @@ contract TokenizedStrategy { StrategyData storage S, address owner ) internal view returns (uint256 maxRedeem_) { + // Cannot redeem when paused. + if (S.paused) return 0; + // Get the max the owner could withdraw currently. maxRedeem_ = IBaseStrategy(address(this)).availableWithdrawLimit(owner); @@ -1181,7 +1201,7 @@ contract TokenizedStrategy { } S.lastTotalAssets = newTotalAssets; - S.lastAccrual = uint80(block.timestamp); + S.lastAccrual = uint72(block.timestamp); emit Accrued(profit, loss, protocolFees, totalFees - protocolFees); } @@ -1535,10 +1555,30 @@ contract TokenizedStrategy { emit StrategyShutdown(); } + /** + * @notice Used to set the pause status for user facing 4626 functions. + * @dev Pausing can be called by the current `management` or `emergencyAdmin`. + * Unpausing can only be called by the current `management`. + * + * This will stop {deposit}, {mint}, {withdraw} and {redeem}, but will + * leave management functions live so the strategy can still be tended, + * reported, configured, shutdown or manually withdrawn in an emergency. + */ + function setPaused(bool paused) external { + if (paused) { + requireEmergencyAuthorized(msg.sender); + } else { + requireManagement(msg.sender); + } + _strategyStorage().paused = paused; + + emit UpdatePaused(paused); + } + /** * @notice To manually withdraw funds from the yield source after a * strategy has been shutdown. - * @dev This can only be called post {shutdownStrategy}. + * @dev This can only be called when the strategy is paused or shutdown. * * This will never cause a change in PPS. Total assets will * be the same before and after. @@ -1551,8 +1591,10 @@ contract TokenizedStrategy { function emergencyWithdraw( uint256 amount ) external nonReentrant onlyEmergencyAuthorized { - // Make sure the strategy has been shutdown. - require(_strategyStorage().shutdown, "not shutdown"); + StrategyData storage S = _strategyStorage(); + + // Make sure the strategy has been paused or shutdown. + require(S.paused || S.shutdown, "not paused or shutdown"); // Withdraw from the yield source. IBaseStrategy(address(this)).shutdownWithdraw(amount); @@ -1701,6 +1743,14 @@ contract TokenizedStrategy { return _strategyStorage().shutdown; } + /** + * @notice To check if the strategy has been paused. + * @return . Whether or not the strategy is paused. + */ + function isPaused() external view returns (bool) { + return _strategyStorage().paused; + } + /*////////////////////////////////////////////////////////////// SETTER FUNCTIONS //////////////////////////////////////////////////////////////*/ diff --git a/src/interfaces/IEvents.sol b/src/interfaces/IEvents.sol index bc6d1fb..9aac8f5 100644 --- a/src/interfaces/IEvents.sol +++ b/src/interfaces/IEvents.sol @@ -11,6 +11,11 @@ interface IEvents { */ event StrategyShutdown(); + /** + * @notice Emitted when a strategies paused status is updated. + */ + event UpdatePaused(bool paused); + /** * @notice Emitted on the initialization of any new `strategy` that uses `asset` * with this specific `apiVersion`. diff --git a/src/interfaces/ITokenizedStrategy.sol b/src/interfaces/ITokenizedStrategy.sol index ea5f9db..ca709d3 100644 --- a/src/interfaces/ITokenizedStrategy.sol +++ b/src/interfaces/ITokenizedStrategy.sol @@ -13,6 +13,8 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { event StrategyShutdown(); + event UpdatePaused(bool paused); + event NewTokenizedStrategy( address indexed strategy, address indexed asset, @@ -149,6 +151,8 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { function isShutdown() external view returns (bool); + function isPaused() external view returns (bool); + function unlockedShares() external view returns (uint256); /*////////////////////////////////////////////////////////////// @@ -175,5 +179,7 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { function shutdownStrategy() external; + function setPaused(bool paused) external; + function emergencyWithdraw(uint256 _amount) external; } diff --git a/src/libraries/TokenizedStrategyLib.sol b/src/libraries/TokenizedStrategyLib.sol index fba706b..ef0d2a6 100644 --- a/src/libraries/TokenizedStrategyLib.sol +++ b/src/libraries/TokenizedStrategyLib.sol @@ -31,7 +31,8 @@ library TokenizedStrategyLib { address emergencyAdmin; uint8 entered; bool shutdown; - uint80 lastAccrual; + bool paused; + uint72 lastAccrual; } function strategyStorage() internal pure returns (StrategyData storage S) { @@ -126,6 +127,10 @@ library TokenizedStrategyLib { return strategyStorage().shutdown; } + function isPaused() internal view returns (bool) { + return strategyStorage().paused; + } + function totalAssets() internal view returns (uint256) { return ITokenizedStrategy(address(this)).totalAssets(); } diff --git a/src/test/Pause.t.sol b/src/test/Pause.t.sol new file mode 100644 index 0000000..f124ddb --- /dev/null +++ b/src/test/Pause.t.sol @@ -0,0 +1,336 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity >=0.8.18; + +import {Setup} from "./utils/Setup.sol"; + +contract PauseTest is Setup { + bytes32 internal constant PERMIT_TYPEHASH = + keccak256( + "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" + ); + + function setUp() public override { + super.setUp(); + } + + function test_pauseAccessControl(address _address) public { + vm.assume(_address != management && _address != emergencyAdmin); + + assertTrue(!strategy.isPaused()); + + vm.prank(_address); + vm.expectRevert("!emergency authorized"); + strategy.setPaused(true); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit UpdatePaused(true); + + vm.prank(management); + strategy.setPaused(true); + + assertTrue(strategy.isPaused()); + + vm.prank(_address); + vm.expectRevert("!management"); + strategy.setPaused(false); + + vm.prank(emergencyAdmin); + vm.expectRevert("!management"); + strategy.setPaused(false); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit UpdatePaused(false); + + vm.prank(management); + strategy.setPaused(false); + + assertTrue(!strategy.isPaused()); + + vm.expectEmit(true, true, true, true, address(strategy)); + emit UpdatePaused(true); + + vm.prank(emergencyAdmin); + strategy.setPaused(true); + + assertTrue(strategy.isPaused()); + } + + function test_pauseBlocks4626UserFlows( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + + vm.prank(emergencyAdmin); + strategy.setPaused(true); + + assertTrue(strategy.isPaused()); + assertEq(strategy.maxDeposit(_address), 0); + assertEq(strategy.maxMint(_address), 0); + assertEq(strategy.maxWithdraw(_address), 0); + assertEq(strategy.maxRedeem(_address), 0); + assertEq(strategy.maxWithdraw(_address, 0), 0); + assertEq(strategy.maxRedeem(_address, MAX_BPS), 0); + + vm.prank(_address); + vm.expectRevert("paused"); + strategy.deposit(1, _address); + + vm.prank(_address); + vm.expectRevert("paused"); + strategy.mint(1, _address); + + vm.prank(_address); + vm.expectRevert("paused"); + strategy.withdraw(1, _address, _address); + + vm.prank(_address); + vm.expectRevert("paused"); + strategy.withdraw(1, _address, _address, 0); + + vm.prank(_address); + vm.expectRevert("paused"); + strategy.redeem(1, _address, _address); + + vm.prank(_address); + vm.expectRevert("paused"); + strategy.redeem(1, _address, _address, MAX_BPS); + } + + function test_unpauseRestores4626Flows( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + + vm.prank(management); + strategy.setPaused(true); + + vm.prank(management); + strategy.setPaused(false); + + assertTrue(!strategy.isPaused()); + assertEq(strategy.maxRedeem(_address), _amount); + + uint256 before = asset.balanceOf(_address); + + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + assertEq(asset.balanceOf(_address), before + _amount); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_unpauseDoesNotUndoShutdown( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + + vm.prank(management); + strategy.setPaused(true); + + vm.prank(emergencyAdmin); + strategy.shutdownStrategy(); + + vm.prank(management); + strategy.setPaused(false); + + assertTrue(!strategy.isPaused()); + assertTrue(strategy.isShutdown()); + assertEq(strategy.maxDeposit(_address), 0); + assertEq(strategy.maxMint(_address), 0); + + asset.mint(_address, _amount); + vm.prank(_address); + asset.approve(address(strategy), _amount); + + vm.prank(_address); + vm.expectRevert("ERC4626: deposit more than max"); + strategy.deposit(_amount, _address); + } + + function test_emergencyWithdrawWhenPaused( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + mintAndDepositIntoStrategy(strategy, _address, _amount); + + vm.prank(emergencyAdmin); + strategy.setPaused(true); + + uint256 toWithdraw = _amount / 2; + + vm.prank(emergencyAdmin); + strategy.emergencyWithdraw(toWithdraw); + + checkStrategyTotals( + strategy, + _amount, + _amount - toWithdraw, + toWithdraw, + _amount + ); + assertEq(asset.balanceOf(address(strategy)), toWithdraw); + assertTrue(!strategy.isShutdown()); + } + + function test_pauseLeavesERC20ShareFunctionsLive() public { + uint256 ownerSk = 0xA11CE; + address owner = vm.addr(ownerSk); + address spender = address(0xBEEF); + address recipient = address(0xCAFE); + uint256 amount = 100 * wad; + uint256 slice = amount / 4; + + mintAndDepositIntoStrategy(strategy, owner, amount); + + vm.prank(management); + strategy.setPaused(true); + + vm.prank(owner); + assertTrue(strategy.transfer(recipient, slice)); + + vm.prank(owner); + assertTrue(strategy.approve(spender, slice)); + assertEq(strategy.allowance(owner, spender), slice); + + vm.prank(spender); + assertTrue(strategy.transferFrom(owner, recipient, slice)); + assertEq(strategy.allowance(owner, spender), 0); + + _permit(owner, spender, slice, block.timestamp + 1 days, ownerSk); + + assertEq(strategy.allowance(owner, spender), slice); + assertEq(strategy.balanceOf(recipient), slice * 2); + assertEq(strategy.balanceOf(owner), amount - slice * 2); + } + + function test_pauseLeavesManagementFunctionsLive() public { + uint256 amount = 100 * wad; + uint256 profit = 10 * wad; + uint256 idle = 5 * wad; + address pendingManagement = address(0xB0B); + address newKeeper = address(0xCA11); + address newEmergencyAdmin = address(0xEAA); + address newPerformanceFeeRecipient = address(0xFEE); + string memory newName = "Paused Strategy"; + + mintAndDepositIntoStrategy(strategy, user, amount); + + vm.prank(emergencyAdmin); + strategy.setPaused(true); + + vm.prank(management); + strategy.setPendingManagement(pendingManagement); + assertEq(strategy.pendingManagement(), pendingManagement); + + vm.prank(management); + strategy.setName(newName); + assertEq(strategy.name(), newName); + + vm.prank(management); + strategy.setPerformanceFee(1_234); + assertEq(strategy.performanceFee(), 1_234); + + vm.prank(management); + strategy.setPerformanceFeeRecipient(newPerformanceFeeRecipient); + assertEq( + strategy.performanceFeeRecipient(), + newPerformanceFeeRecipient + ); + + vm.prank(management); + strategy.setProfitMaxUnlockTime(7 days); + assertEq(strategy.profitMaxUnlockTime(), 7 days); + + vm.prank(management); + strategy.setKeeper(newKeeper); + assertEq(strategy.keeper(), newKeeper); + + vm.prank(management); + strategy.setEmergencyAdmin(newEmergencyAdmin); + assertEq(strategy.emergencyAdmin(), newEmergencyAdmin); + + queueHarvestProfit(strategy, profit); + + vm.prank(newKeeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + assertEq(reportedProfit, profit); + assertEq(reportedLoss, 0); + + asset.mint(address(strategy), idle); + + vm.prank(newKeeper); + strategy.tend(); + assertEq(asset.balanceOf(address(strategy)), 0); + + vm.prank(newEmergencyAdmin); + strategy.shutdownStrategy(); + assertTrue(strategy.isShutdown()); + assertTrue(strategy.isPaused()); + } + + function test_emergencyWithdrawNotPausedOrShutdownReverts() public { + vm.prank(management); + vm.expectRevert("not paused or shutdown"); + strategy.emergencyWithdraw(0); + } + + function _permit( + address owner, + address spender, + uint256 amount, + uint256 deadline, + uint256 ownerSk + ) internal { + bytes32 structHash = keccak256( + abi.encode( + PERMIT_TYPEHASH, + owner, + spender, + amount, + strategy.nonces(owner), + deadline + ) + ); + bytes32 digest = keccak256( + abi.encodePacked( + "\x19\x01", + strategy.DOMAIN_SEPARATOR(), + structHash + ) + ); + (uint8 v, bytes32 r, bytes32 s) = vm.sign(ownerSk, digest); + + strategy.permit(owner, spender, amount, deadline, v, r, s); + } +} diff --git a/src/test/Shutdown.t.sol b/src/test/Shutdown.t.sol index 78580cc..5ff7a63 100644 --- a/src/test/Shutdown.t.sol +++ b/src/test/Shutdown.t.sol @@ -347,7 +347,7 @@ contract ShutdownTest is Setup { uint256 toWithdraw = _amount / 2; - vm.expectRevert("not shutdown"); + vm.expectRevert("not paused or shutdown"); vm.prank(management); strategy.emergencyWithdraw(toWithdraw); } diff --git a/src/test/TokenizedStrategyLibViews.t.sol b/src/test/TokenizedStrategyLibViews.t.sol index c4e0965..f90cee0 100644 --- a/src/test/TokenizedStrategyLibViews.t.sol +++ b/src/test/TokenizedStrategyLibViews.t.sol @@ -166,6 +166,11 @@ contract TokenizedStrategyLibViewsTest is Setup { strategy.isShutdown(), "isShutdown" ); + assertEq( + libraryStrategy.libraryIsPaused(), + strategy.isPaused(), + "isPaused" + ); assertEq( libraryStrategy.libraryTotalAssets(), strategy.totalAssets(), diff --git a/src/test/mocks/MockStorage.sol b/src/test/mocks/MockStorage.sol index ab4351a..a1e3c46 100644 --- a/src/test/mocks/MockStorage.sol +++ b/src/test/mocks/MockStorage.sol @@ -45,5 +45,6 @@ contract MockStorage { // Strategy status checks. uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. bool shutdown; // Bool that can be used to stop deposits into the strategy. - uint80 lastAccrual; // The last time accounting synced. + bool paused; // Bool that can be used to stop user facing 4626 functions. + uint72 lastAccrual; // The last time accounting synced. } diff --git a/src/test/mocks/MockStrategy.sol b/src/test/mocks/MockStrategy.sol index 807cf1a..8b6b763 100644 --- a/src/test/mocks/MockStrategy.sol +++ b/src/test/mocks/MockStrategy.sol @@ -158,6 +158,10 @@ contract MockStrategy is BaseStrategy { return TokenizedStrategy.isShutdown(); } + function libraryIsPaused() external view returns (bool) { + return TokenizedStrategy.isPaused(); + } + function libraryTotalAssets() external view returns (uint256) { return TokenizedStrategy.totalAssets(); } From 729b9700034362909086a71aab9b4ae5352812b5 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Mon, 1 Jun 2026 16:25:58 -0600 Subject: [PATCH 19/27] chore: spech --- SPECIFICATION.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/SPECIFICATION.md b/SPECIFICATION.md index ea1b4cd..0de3873 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -87,9 +87,9 @@ Users can deposit ASSET tokens to receive shares. Deposits are limited by the availableDepositLimit function that can be changed by the strategist if non uint256.max values are desired. #### Withdrawals / Redeems -Users can redeem their shares at any point in time if there is liquidity available. +Users can redeem their shares when the strategy is not paused and there is liquidity available. -The amount of a withdraw or redeem can be limited by the strategist by overriding the availableWithdrawLimit function. +The amount of a withdraw or redeem can be limited by the strategist by overriding the availableWithdrawLimit function. If the strategy is paused, withdraw and redeem are blocked. In order to properly comply with the ERC-4626 standard and still allow losses, both withdraw and redeem have an additional optional parameter of 'maxLoss' that can be used. The default for 'maxLoss' is 0 (i.e. revert if any loss) for withdraws, and 10_000 (100%) for redeems. @@ -169,18 +169,18 @@ This can be customized based on the strategy. Based on aspects such as TVL, expe Strategy Shares are ERC4626 compliant. ## Emergency Operation -There is default emergency functions built in. First of which is `shutdownStrategy`. This can only ever be called by the management address and is non-reversible. +There is default emergency functions built in. First of which is `shutdownStrategy`. This can be called by the management address or emergencyAdmin and is non-reversible. -Once this is called it will stop any further deposit or mints but will have no effect on any other functionality including withdraw, redeem, report and tend. This is to allow management to continue potentially recording profits or losses and users to withdraw even post shutdown. +Once this is called it will stop any further deposit or mints but will have no effect on any other functionality including withdraw, redeem, report and tend. This is to allow management to continue potentially recording profits or losses and users to withdraw even post shutdown. If the strategy is also paused, the pause still blocks deposit, mint, withdraw and redeem until management unpauses. This can be used in an emergency or simply to retire a vault. -Once a strategy is shutdown management can also call `emergencyWithdraw(amount)`. Which will tell the strategy to withdraw a specified `amount` from the yield source and keep it as idle in the vault. This function will also do any needed updates to totalDebt and totalIdle, based on amounts withdrawn to assure withdraws continue to function properly. +Once a strategy is shutdown or paused, management or emergencyAdmin can also call `emergencyWithdraw(amount)`. Which will tell the strategy to withdraw a specified `amount` from the yield source and keep it as idle in the vault. This function will also do any needed updates to totalDebt and totalIdle, based on amounts withdrawn to assure withdraws continue to function properly. All other emergency functionality is left up to the individual strategist. ### Withdrawals -Withdrawals can't be paused under any circumstance unless built in a specific implementation. +Withdrawals and redemptions are paused by `setPaused(true)`, which can be called by management or emergencyAdmin. Only management can unpause. Shutdown alone does not pause withdrawals or redemptions; liquidity, `availableWithdrawLimit`, and the paused state determine whether a user can withdraw. ## Use From 0454726e319eef876c96dc628ac8eecf4893f0a3 Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Wed, 3 Jun 2026 10:22:50 -0600 Subject: [PATCH 20/27] test: add constant accrual accounting invariants (#118) * test: add constant accrual accounting invariants * fix: format --- src/test/ConstantAccrualInvariant.t.sol | 167 ++++++ src/test/ProfitLocking.t.sol | 279 ++++++++++ src/test/handlers/ConstantAccrualHandler.sol | 521 +++++++++++++++++++ 3 files changed, 967 insertions(+) create mode 100644 src/test/ConstantAccrualInvariant.t.sol create mode 100644 src/test/handlers/ConstantAccrualHandler.sol diff --git a/src/test/ConstantAccrualInvariant.t.sol b/src/test/ConstantAccrualInvariant.t.sol new file mode 100644 index 0000000..8d3dc64 --- /dev/null +++ b/src/test/ConstantAccrualInvariant.t.sol @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity >=0.8.18; + +import {BaseInvariant} from "./utils/BaseInvariant.sol"; +import {ConstantAccrualHandler} from "./handlers/ConstantAccrualHandler.sol"; + +contract ConstantAccrualInvariantTest is BaseInvariant { + address internal constant DEAD_ADDRESS = + 0x000000000000000000000000000000000000dEaD; + + ConstantAccrualHandler public constantAccrualHandler; + + function setUp() public override { + super.setUp(); + + setFees(100, 1_000); + + constantAccrualHandler = new ConstantAccrualHandler(); + + excludeSender(address(0)); + excludeSender(address(strategy)); + excludeSender(address(asset)); + excludeSender(address(yieldSource)); + excludeSender(keeper); + excludeSender(management); + excludeSender(emergencyAdmin); + excludeSender(protocolFeeRecipient); + excludeSender(performanceFeeRecipient); + excludeSender(DEAD_ADDRESS); + + targetContract(address(constantAccrualHandler)); + + targetSelector( + FuzzSelector({ + addr: address(constantAccrualHandler), + selectors: getTargetSelectors() + }) + ); + } + + function invariant_latchedAssets() public { + if (strategy.lastAccrual() == block.timestamp) { + assertEq( + strategy.totalAssets(), + strategy.lastTotalAssets(), + "latched assets" + ); + } else { + assertEq( + strategy.totalAssets(), + constantAccrualHandler.actualAssets(), + "unlatched assets" + ); + } + } + + function invariant_bufferAccounting() public { + uint256 unlockedShares = strategy.unlockedShares(); + uint256 rawBuffer = constantAccrualHandler.rawStrategyBuffer(); + uint256 visibleBuffer = strategy.balanceOf(address(strategy)); + uint256 fullProfitUnlockDate = strategy.fullProfitUnlockDate(); + uint256 profitUnlockingRate = strategy.profitUnlockingRate(); + + if (fullProfitUnlockDate == 0) { + assertEq(rawBuffer, 0, "date cleared with buffer"); + } + + if (profitUnlockingRate > 0 && fullProfitUnlockDate > block.timestamp) { + assertGt(rawBuffer, 0, "rate without buffer"); + assertGt(visibleBuffer, 0, "future unlock without visible buffer"); + assertLt(unlockedShares, rawBuffer, "fully unlocked before date"); + } + + if ( + fullProfitUnlockDate != 0 && fullProfitUnlockDate <= block.timestamp + ) { + assertEq(visibleBuffer, 0, "expired visible buffer"); + assertEq( + unlockedShares, + rawBuffer, + "expired buffer not fully unlocked" + ); + } + } + + function invariant_supplyConservation() public { + assertApproxEq( + strategy.totalSupply(), + constantAccrualHandler.trackedSupply(), + 1, + "tracked supply" + ); + } + + function invariant_handlerAccountingProperties() public { + assertEq( + constantAccrualHandler.accountingViolations(), + 0, + "handler accounting violation" + ); + } + + function invariant_maxWithdraw() public { + assert_maxWithdraw(); + } + + function invariant_maxRedeem() public { + assert_maxRedeem(); + } + + function invariant_maxWithdrawEqualsMaxRedeem() public { + assert_maxRedeemEqualsMaxWithdraw(); + } + + function invariant_previewMintAndConvertToAssets() public { + assert_previewMintAndConvertToAssets(); + } + + function invariant_previewWithdrawAndConvertToShares() public { + assert_previewWithdrawAndConvertToShares(); + } + + function invariant_callSummary() public view { + constantAccrualHandler.callSummary(); + } + + function test_wiredConstantAccrualHandlerActionsDoNotRevert() public { + constantAccrualHandler.deposit(1e18); + constantAccrualHandler.liveProfit(1e17); + skip(1); + constantAccrualHandler.syncViaManagementSetter(); + constantAccrualHandler.sameBlockDoubleAccrual(1e17); + constantAccrualHandler.setProfitMaxUnlockTime(0); + assertEq( + constantAccrualHandler.accountingViolations(), + 0, + "handler accounting violation" + ); + } + + function getTargetSelectors() + internal + view + returns (bytes4[] memory selectors) + { + selectors = new bytes4[](19); + selectors[0] = constantAccrualHandler.deposit.selector; + selectors[1] = constantAccrualHandler.mint.selector; + selectors[2] = constantAccrualHandler.withdraw.selector; + selectors[3] = constantAccrualHandler.redeem.selector; + selectors[4] = constantAccrualHandler.liveProfit.selector; + selectors[5] = constantAccrualHandler.liveLoss.selector; + selectors[6] = constantAccrualHandler.queueReportProfit.selector; + selectors[7] = constantAccrualHandler.queueReportLoss.selector; + selectors[8] = constantAccrualHandler.report.selector; + selectors[9] = constantAccrualHandler.reportWithQueuedProfit.selector; + selectors[10] = constantAccrualHandler.reportWithQueuedLoss.selector; + selectors[11] = constantAccrualHandler.tendNeutral.selector; + selectors[12] = constantAccrualHandler.skipSmall.selector; + selectors[13] = constantAccrualHandler.skipToHalfUnlock.selector; + selectors[14] = constantAccrualHandler.skipPastUnlock.selector; + selectors[15] = constantAccrualHandler.setFees.selector; + selectors[16] = constantAccrualHandler.syncViaManagementSetter.selector; + selectors[17] = constantAccrualHandler.sameBlockDoubleAccrual.selector; + selectors[18] = constantAccrualHandler.setProfitMaxUnlockTime.selector; + } +} diff --git a/src/test/ProfitLocking.t.sol b/src/test/ProfitLocking.t.sol index c2c047a..012cdf9 100644 --- a/src/test/ProfitLocking.t.sol +++ b/src/test/ProfitLocking.t.sol @@ -2706,4 +2706,283 @@ contract ProfitLockingTest is Setup { "buffer fully drained" ); } + + function test_liveLossThenReportLossTwoStagePartialBufferBurn() public { + uint256 amount = 1_000e18; + uint256 profit = 200e18; + uint256 liveLoss = 20e18; + uint256 reportLoss = 20e18; + address depositor = address(0xCAFE01); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + createAndCheckProfit(strategy, profit, 0, 0); + + skip(profitMaxUnlockTime / 2); + + uint256 rawBefore = _rawLockedBuffer(); + assertGt(rawBefore, 0, "!rawBefore"); + + yieldSource.simulateLoss(liveLoss); + queueHarvestLoss(strategy, reportLoss); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, reportLoss, "!loss"); + + uint256 rawAfter = _rawLockedBuffer(); + assertGt(rawAfter, 0, "!rawAfter"); + assertLt(rawAfter, rawBefore, "!burned"); + assertGt(strategy.fullProfitUnlockDate(), block.timestamp, "!date"); + assertGt(strategy.profitUnlockingRate(), 0, "!rate"); + } + + function test_liveLossThenReportLossFullyDrainsBuffer() public { + uint256 amount = 1_000e18; + uint256 profit = 200e18; + uint256 liveLoss = 500e18; + uint256 reportLoss = 50e18; + address depositor = address(0xCAFE02); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + createAndCheckProfit(strategy, profit, 0, 0); + + skip(profitMaxUnlockTime / 2); + + assertGt(_rawLockedBuffer(), 0, "!rawBefore"); + + yieldSource.simulateLoss(liveLoss); + queueHarvestLoss(strategy, reportLoss); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, reportLoss, "!loss"); + assertEq(_rawLockedBuffer(), 0, "!rawAfter"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); + assertEq(strategy.fullProfitUnlockDate(), 0, "!date"); + } + + function test_liveLossFullyDrainsBufferThenReportLossHitsPps() public { + uint256 amount = 1_000e18; + uint256 profit = 200e18; + uint256 liveLoss = 500e18; + uint256 reportLoss = 200e18; + address depositor = address(0xCAFE03); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + createAndCheckProfit(strategy, profit, 0, 0); + + skip(profitMaxUnlockTime / 2); + + yieldSource.simulateLoss(liveLoss); + + vm.prank(management); + strategy.setPerformanceFeeRecipient(performanceFeeRecipient); + + assertEq(_rawLockedBuffer(), 0, "!drained"); + + uint256 ppsBeforeReport = strategy.pricePerShare(); + + queueHarvestLoss(strategy, reportLoss); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, reportLoss, "!loss"); + assertEq(_rawLockedBuffer(), 0, "!rawAfter"); + assertLt(strategy.pricePerShare(), ppsBeforeReport, "!pps"); + } + + function test_liveProfitAccruesFeesThenReportLoss() public { + uint256 amount = 1_000e18; + uint256 liveProfit = 100e18; + uint256 reportLoss = 50e18; + address depositor = address(0xCAFE04); + + setFees(100, 1_000); + mintAndDepositIntoStrategy(strategy, depositor, amount); + + skip(1); + + asset.mint(address(yieldSource), liveProfit); + queueHarvestLoss(strategy, reportLoss); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, reportLoss, "!loss"); + assertEq(strategy.totalAssets(), amount + liveProfit - reportLoss); + assertGt(strategy.balanceOf(performanceFeeRecipient), 0, "!fees"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!buffer"); + } + + function test_liveLossThenReportProfitOnlyLocksQueuedProfit() public { + uint256 amount = 1_000e18; + uint256 liveLoss = 50e18; + uint256 reportProfit = 100e18; + address depositor = address(0xCAFE05); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + + skip(1); + + yieldSource.simulateLoss(liveLoss); + queueHarvestProfit(strategy, reportProfit); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, reportProfit, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq(strategy.totalAssets(), amount - liveLoss + reportProfit); + assertApproxEq( + strategy.convertToAssets(_rawLockedBuffer()), + reportProfit, + 10, + "!locked" + ); + } + + function test_secondReportSameBlockAfterQueuedProfitIsNoop() public { + uint256 amount = 1_000e18; + uint256 profit = 100e18; + address depositor = address(0xCAFE06); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + queueHarvestProfit(strategy, profit); + + vm.prank(keeper); + (uint256 firstProfit, uint256 firstLoss) = strategy.report(); + + assertEq(firstProfit, profit, "!firstProfit"); + assertEq(firstLoss, 0, "!firstLoss"); + + uint256 rawBefore = _rawLockedBuffer(); + uint256 dateBefore = strategy.fullProfitUnlockDate(); + uint256 rateBefore = strategy.profitUnlockingRate(); + uint256 assetsBefore = strategy.totalAssets(); + + vm.prank(keeper); + (uint256 secondProfit, uint256 secondLoss) = strategy.report(); + + assertEq(secondProfit, 0, "!secondProfit"); + assertEq(secondLoss, 0, "!secondLoss"); + assertEq(_rawLockedBuffer(), rawBefore, "!raw"); + assertEq(strategy.fullProfitUnlockDate(), dateBefore, "!date"); + assertEq(strategy.profitUnlockingRate(), rateBefore, "!rate"); + assertEq(strategy.totalAssets(), assetsBefore, "!assets"); + } + + function test_secondAccrualTriggerSameBlockIsLatched() public { + uint256 amount = 1_000e18; + uint256 firstLiveProfit = 100e18; + uint256 secondLiveProfit = 50e18; + address depositor = address(0xCAFE09); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + + skip(1); + + asset.mint(address(yieldSource), firstLiveProfit); + + vm.prank(management); + strategy.setPerformanceFeeRecipient(performanceFeeRecipient); + + assertEq(strategy.lastAccrual(), block.timestamp, "!accrual"); + assertEq(strategy.lastTotalAssets(), amount + firstLiveProfit); + + uint256 assetsAfterFirstSync = strategy.totalAssets(); + uint256 ppsAfterFirstSync = strategy.pricePerShare(); + uint256 lastTotalAssetsAfterFirstSync = strategy.lastTotalAssets(); + + asset.mint(address(yieldSource), secondLiveProfit); + + vm.prank(management); + strategy.setPerformanceFeeRecipient(performanceFeeRecipient); + + assertEq(strategy.lastTotalAssets(), lastTotalAssetsAfterFirstSync); + assertEq(strategy.totalAssets(), assetsAfterFirstSync); + assertEq(strategy.pricePerShare(), ppsAfterFirstSync); + + skip(1); + + assertEq( + strategy.totalAssets(), + amount + firstLiveProfit + secondLiveProfit, + "!unlatched" + ); + } + + function test_repeatedNoopReportsOnlyDrainUnlockingBuffer() public { + uint256 amount = 1_000e18; + uint256 profit = 100e18; + address depositor = address(0xCAFE07); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + createAndCheckProfit(strategy, profit, 0, 0); + + uint256 previousRaw = _rawLockedBuffer(); + assertGt(previousRaw, 0, "!raw"); + + for (uint256 i; i < 3; ++i) { + skip(1 days); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertLe(_rawLockedBuffer(), previousRaw, "!monotonic"); + previousRaw = _rawLockedBuffer(); + } + + skip(profitMaxUnlockTime + 1); + + vm.prank(keeper); + strategy.report(); + + assertEq(_rawLockedBuffer(), 0, "!rawAfter"); + assertEq(strategy.fullProfitUnlockDate(), 0, "!date"); + } + + function test_expiredUnlockNoopReportClearsRawBuffer() public { + uint256 amount = 1_000e18; + uint256 profit = 100e18; + address depositor = address(0xCAFE08); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, depositor, amount); + createAndCheckProfit(strategy, profit, 0, 0); + + skip(profitMaxUnlockTime + 1); + + assertGt(strategy.unlockedShares(), 0, "!unlocked"); + assertEq(strategy.balanceOf(address(strategy)), 0, "!visible"); + assertGt(_rawLockedBuffer(), 0, "!rawBefore"); + + vm.prank(keeper); + (uint256 reportedProfit, uint256 reportedLoss) = strategy.report(); + + assertEq(reportedProfit, 0, "!profit"); + assertEq(reportedLoss, 0, "!loss"); + assertEq(_rawLockedBuffer(), 0, "!rawAfter"); + assertEq(strategy.fullProfitUnlockDate(), 0, "!date"); + } + + function _rawLockedBuffer() internal view returns (uint256) { + return + strategy.balanceOf(address(strategy)) + strategy.unlockedShares(); + } } diff --git a/src/test/handlers/ConstantAccrualHandler.sol b/src/test/handlers/ConstantAccrualHandler.sol new file mode 100644 index 0000000..24f82aa --- /dev/null +++ b/src/test/handlers/ConstantAccrualHandler.sol @@ -0,0 +1,521 @@ +// SPDX-License-Identifier: AGPL-3.0 +pragma solidity >=0.8.18; + +import "forge-std/console.sol"; +import {ExtendedTest} from "../utils/ExtendedTest.sol"; +import {Setup, IMockStrategy, ERC20Mock} from "../utils/Setup.sol"; +import {LibAddressSet, AddressSet} from "../utils/LibAddressSet.sol"; +import {MockYieldSource} from "../mocks/MockYieldSource.sol"; + +contract ConstantAccrualHandler is ExtendedTest { + using LibAddressSet for AddressSet; + + address internal constant DEAD_ADDRESS = + 0x000000000000000000000000000000000000dEaD; + + Setup public setup; + IMockStrategy public strategy; + ERC20Mock public asset; + MockYieldSource public yieldSource; + + uint256 public maxFuzzAmount = 1e30; + uint256 public minFuzzAmount = 10_000; + uint256 public MAX_BPS = 10_000; + + uint256 public ghost_depositSum; + uint256 public ghost_withdrawSum; + uint256 public ghost_liveProfitSum; + uint256 public ghost_liveLossSum; + uint256 public ghost_reportProfitSum; + uint256 public ghost_reportLossSum; + uint256 public ghost_pendingQueuedProfit; + uint256 public ghost_pendingQueuedLoss; + + uint256 public liveProfitReportProfit; + uint256 public liveProfitReportLoss; + uint256 public liveLossReportProfit; + uint256 public liveLossReportLoss; + uint256 public noopReports; + uint256 public tendNeutralChecks; + uint256 public sameBlockIdempotentChecks; + uint256 public activeUnlockLossBurns; + uint256 public liveProfitNoBufferChecks; + uint256 public queuedDeltaReportChecks; + uint256 public zeroUnlockTimeChecks; + uint256 public accountingViolations; + + bool public pendingLiveProfit; + bool public pendingLiveLoss; + bool public pendingLiveProfitNoBuffer; + + mapping(bytes32 => uint256) public calls; + + AddressSet internal _actors; + address internal actor; + + modifier createActor() { + actor = msg.sender; + _actors.add(msg.sender); + _; + } + + modifier useActor(uint256 actorIndexSeed) { + _ensureActor(); + actor = _actors.rand(actorIndexSeed); + _; + } + + modifier countCall(bytes32 key) { + calls[key]++; + _; + } + + constructor() { + setup = Setup(msg.sender); + asset = setup.asset(); + strategy = setup.strategy(); + yieldSource = MockYieldSource(strategy.yieldSource()); + skip(10); + } + + function deposit(uint256 amount) public createActor countCall("deposit") { + amount = bound(amount, minFuzzAmount, maxFuzzAmount); + if (strategy.previewDeposit(amount) == 0) return; + + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + + _depositFor(actor, amount); + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + + ghost_depositSum += amount; + } + + function mint(uint256 shares) public createActor countCall("mint") { + shares = bound(shares, minFuzzAmount, maxFuzzAmount); + + uint256 assets = strategy.previewMint(shares); + if (assets == 0) return; + + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + + asset.mint(actor, assets); + + vm.prank(actor); + asset.approve(address(strategy), assets); + + vm.prank(actor); + uint256 deposited = strategy.mint(shares, actor); + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + + ghost_depositSum += deposited; + } + + function withdraw( + uint256 actorSeed, + uint256 amount + ) public useActor(actorSeed) countCall("withdraw") { + uint256 maxWithdraw = strategy.maxWithdraw(actor); + if (maxWithdraw == 0) return; + + amount = bound(amount, 0, maxWithdraw); + if (amount == 0) return; + + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + + vm.prank(actor); + strategy.withdraw(amount, actor, actor, MAX_BPS); + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + + ghost_withdrawSum += amount; + } + + function redeem( + uint256 actorSeed, + uint256 shares + ) public useActor(actorSeed) countCall("redeem") { + uint256 maxRedeem = strategy.maxRedeem(actor); + if (maxRedeem == 0) return; + + shares = bound(shares, 0, maxRedeem); + if (shares == 0) return; + if (strategy.previewRedeem(shares) == 0) return; + + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + + vm.prank(actor); + uint256 assets = strategy.redeem(shares, actor, actor, MAX_BPS); + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + + ghost_withdrawSum += assets; + } + + function liveProfit(uint256 amount) public countCall("liveProfit") { + _ensureActor(); + uint256 rawBufferBefore = rawStrategyBuffer(); + amount = _boundDelta(amount); + + asset.mint(address(yieldSource), amount); + + ghost_liveProfitSum += amount; + pendingLiveProfit = true; + + if (rawBufferBefore == 0) { + pendingLiveProfitNoBuffer = true; + } + } + + function liveLoss(uint256 amount) public countCall("liveLoss") { + _ensureActor(); + uint256 available = yieldSource.balance(); + if (available <= ghost_pendingQueuedLoss) return; + available -= ghost_pendingQueuedLoss; + if (available == 0) return; + + amount = bound(amount, 1, available / 2 == 0 ? 1 : available / 2); + uint256 rawBufferBefore = rawStrategyBuffer(); + + yieldSource.simulateLoss(amount); + + ghost_liveLossSum += amount; + pendingLiveLoss = true; + + if ( + rawBufferBefore != 0 && + strategy.fullProfitUnlockDate() > block.timestamp + ) { + activeUnlockLossBurns++; + } + } + + function queueReportProfit( + uint256 amount + ) public countCall("queueReportProfit") { + _ensureActor(); + amount = _boundDelta(amount); + + asset.mint(address(yieldSource), amount); + yieldSource.queueRewards(amount); + + ghost_pendingQueuedProfit += amount; + } + + function queueReportLoss( + uint256 amount + ) public countCall("queueReportLoss") { + _ensureActor(); + uint256 available = yieldSource.balance(); + if (available <= ghost_pendingQueuedLoss) return; + + available -= ghost_pendingQueuedLoss; + if (available == 0) return; + + amount = bound(amount, 1, available / 2 == 0 ? 1 : available / 2); + yieldSource.queueLoss(amount); + + ghost_pendingQueuedLoss += amount; + } + + function report() public countCall("report") { + bool hadLiveProfit = pendingLiveProfit; + bool hadLiveLoss = pendingLiveLoss; + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + bool accrualCanRun = strategy.lastAccrual() != block.timestamp; + uint256 expectedProfit; + uint256 expectedLoss; + + if (ghost_pendingQueuedProfit > ghost_pendingQueuedLoss) { + expectedProfit = + ghost_pendingQueuedProfit - + ghost_pendingQueuedLoss; + } else { + expectedLoss = ghost_pendingQueuedLoss - ghost_pendingQueuedProfit; + } + + vm.prank(setup.keeper()); + (uint256 profit, uint256 loss) = strategy.report(); + + ghost_reportProfitSum += profit; + ghost_reportLossSum += loss; + + if (accrualCanRun) { + if (profit != expectedProfit || loss != expectedLoss) { + accountingViolations++; + } else { + queuedDeltaReportChecks++; + } + } + + if ( + accrualCanRun && hadPendingLiveProfitNoBuffer && expectedProfit == 0 + ) { + if (rawStrategyBuffer() != 0) { + accountingViolations++; + } else { + liveProfitNoBufferChecks++; + } + } + + if (hadLiveProfit && profit != 0) liveProfitReportProfit++; + if (hadLiveProfit && loss != 0) liveProfitReportLoss++; + if (hadLiveLoss && profit != 0) liveLossReportProfit++; + if (hadLiveLoss && loss != 0) liveLossReportLoss++; + if ( + !hadLiveProfit && + !hadLiveLoss && + expectedProfit == 0 && + expectedLoss == 0 && + profit == 0 && + loss == 0 + ) { + noopReports++; + } + + ghost_pendingQueuedProfit = 0; + ghost_pendingQueuedLoss = 0; + pendingLiveProfit = false; + pendingLiveLoss = false; + pendingLiveProfitNoBuffer = false; + } + + function reportWithQueuedProfit( + uint256 amount + ) public countCall("reportWithQueuedProfit") { + queueReportProfit(amount); + report(); + } + + function reportWithQueuedLoss( + uint256 amount + ) public countCall("reportWithQueuedLoss") { + queueReportLoss(amount); + report(); + } + + function syncViaManagementSetter() public countCall("syncViaManagement") { + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + address feeRecipient = setup.performanceFeeRecipient(); + + vm.prank(setup.management()); + strategy.setPerformanceFeeRecipient(feeRecipient); + + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + } + + function sameBlockDoubleAccrual( + uint256 amount + ) public countCall("sameBlockDoubleAccrual") { + _ensureActor(); + skip(1); + + amount = _boundDelta(amount); + asset.mint(address(yieldSource), amount); + pendingLiveProfit = true; + if (rawStrategyBuffer() == 0) pendingLiveProfitNoBuffer = true; + + syncViaManagementSetter(); + + uint256 lastTotalAssetsAfterFirstSync = strategy.lastTotalAssets(); + uint256 totalAssetsAfterFirstSync = strategy.totalAssets(); + + asset.mint(address(yieldSource), amount); + pendingLiveProfit = true; + if (rawStrategyBuffer() == 0) pendingLiveProfitNoBuffer = true; + + syncViaManagementSetter(); + + if ( + strategy.lastAccrual() != block.timestamp || + strategy.lastTotalAssets() != lastTotalAssetsAfterFirstSync || + strategy.totalAssets() != totalAssetsAfterFirstSync + ) { + accountingViolations++; + } else { + sameBlockIdempotentChecks++; + } + } + + function tendNeutral(uint256 amount) public countCall("tendNeutral") { + _ensureActor(); + amount = _boundDelta(amount); + + asset.mint(address(strategy), amount); + + uint256 lastTotalAssetsBefore = strategy.lastTotalAssets(); + uint256 lastAccrualBefore = strategy.lastAccrual(); + uint256 supplyBefore = strategy.totalSupply(); + uint256 ppsBefore = strategy.pricePerShare(); + + vm.prank(setup.keeper()); + strategy.tend(); + + if ( + strategy.lastTotalAssets() != lastTotalAssetsBefore || + strategy.lastAccrual() != lastAccrualBefore || + strategy.totalSupply() != supplyBefore || + strategy.pricePerShare() != ppsBefore + ) { + accountingViolations++; + } else { + tendNeutralChecks++; + } + } + + function skipSmall(uint256 time) public countCall("skipSmall") { + time = bound(time, 1, 1 days); + skip(time); + } + + function skipToHalfUnlock() public countCall("skipHalf") { + skip(setup.profitMaxUnlockTime() / 2); + } + + function skipPastUnlock() public countCall("skipPastUnlock") { + skip(setup.profitMaxUnlockTime() + 1); + } + + function setFees( + uint16 protocolFee, + uint16 performanceFee + ) public countCall("setFees") { + protocolFee = uint16(bound(uint256(protocolFee), 0, 1_000)); + performanceFee = uint16(bound(uint256(performanceFee), 0, 2_000)); + + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + + setup.mockFactory().setFee(protocolFee); + + vm.prank(setup.management()); + strategy.setPerformanceFee(performanceFee); + + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + } + + function setProfitMaxUnlockTime( + uint32 unlockTime + ) public countCall("setProfitMaxUnlockTime") { + uint256 bounded = unlockTime % 5 == 0 + ? 0 + : bound(uint256(unlockTime), 1, 31_556_952); + uint256 lastAccrualBefore = strategy.lastAccrual(); + bool hadPendingLiveProfitNoBuffer = pendingLiveProfitNoBuffer; + + vm.prank(setup.management()); + strategy.setProfitMaxUnlockTime(bounded); + + if (bounded == 0) zeroUnlockTimeChecks++; + + _afterAccrualSync(lastAccrualBefore, hadPendingLiveProfitNoBuffer); + } + + function actualAssets() public view returns (uint256) { + return yieldSource.balance() + asset.balanceOf(address(strategy)); + } + + function rawStrategyBuffer() public view returns (uint256) { + return + strategy.balanceOf(address(strategy)) + strategy.unlockedShares(); + } + + function trackedSupply() public view returns (uint256 supply) { + address[] memory actors = _actors.addresses(); + for (uint256 i; i < actors.length; ++i) { + supply += strategy.balanceOf(actors[i]); + } + + supply += strategy.balanceOf(setup.protocolFeeRecipient()); + supply += strategy.balanceOf(setup.performanceFeeRecipient()); + supply += strategy.balanceOf(DEAD_ADDRESS); + supply += strategy.balanceOf(address(strategy)); + } + + function actorCount() public view returns (uint256) { + return _actors.count(); + } + + function callSummary() external view { + console.log("Constant accrual call summary:"); + console.log("-------------------"); + console.log("deposit", calls["deposit"]); + console.log("mint", calls["mint"]); + console.log("withdraw", calls["withdraw"]); + console.log("redeem", calls["redeem"]); + console.log("live profit", calls["liveProfit"]); + console.log("live loss", calls["liveLoss"]); + console.log("queue report profit", calls["queueReportProfit"]); + console.log("queue report loss", calls["queueReportLoss"]); + console.log("report", calls["report"]); + console.log("report queued profit", calls["reportWithQueuedProfit"]); + console.log("report queued loss", calls["reportWithQueuedLoss"]); + console.log("sync management", calls["syncViaManagement"]); + console.log("same block accrual", calls["sameBlockDoubleAccrual"]); + console.log("set unlock time", calls["setProfitMaxUnlockTime"]); + console.log("tend neutral", calls["tendNeutral"]); + console.log("-------------------"); + console.log("live profit + report profit", liveProfitReportProfit); + console.log("live profit + report loss", liveProfitReportLoss); + console.log("live loss + report profit", liveLossReportProfit); + console.log("live loss + report loss", liveLossReportLoss); + console.log("noop reports", noopReports); + console.log("same block idempotent", sameBlockIdempotentChecks); + console.log("tend neutral checks", tendNeutralChecks); + console.log("live profit no buffer", liveProfitNoBufferChecks); + console.log("queued delta report checks", queuedDeltaReportChecks); + console.log("zero unlock time checks", zeroUnlockTimeChecks); + console.log("active unlock loss burns", activeUnlockLossBurns); + console.log("accounting violations", accountingViolations); + } + + function _afterAccrualSync( + uint256 lastAccrualBefore, + bool hadPendingLiveProfitNoBuffer + ) internal { + if (lastAccrualBefore == block.timestamp) return; + + if (hadPendingLiveProfitNoBuffer) { + if (rawStrategyBuffer() != 0) { + accountingViolations++; + } else { + liveProfitNoBufferChecks++; + } + pendingLiveProfitNoBuffer = false; + } + + pendingLiveProfit = false; + pendingLiveLoss = false; + } + + function _ensureActor() internal { + if (_actors.count() != 0) return; + + actor = address(0xA11CE); + _actors.add(actor); + _depositFor(actor, minFuzzAmount * 100); + ghost_depositSum += minFuzzAmount * 100; + } + + function _depositFor(address receiver, uint256 amount) internal { + if (strategy.previewDeposit(amount) == 0) return; + + asset.mint(receiver, amount); + + vm.prank(receiver); + asset.approve(address(strategy), amount); + + vm.prank(receiver); + strategy.deposit(amount, receiver); + } + + function _boundDelta(uint256 amount) internal view returns (uint256) { + uint256 base = strategy.totalAssets(); + uint256 upper = base == 0 ? minFuzzAmount * 100 : base / 2; + if (upper < minFuzzAmount) upper = minFuzzAmount; + if (upper > maxFuzzAmount) upper = maxFuzzAmount; + return bound(amount, minFuzzAmount, upper); + } +} From a7a1db5c1274729c695afe4e93cf6fbd5e050797 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Mon, 8 Jun 2026 10:02:11 -0600 Subject: [PATCH 21/27] feat: reentrancy --- foundry.toml | 3 +-- src/BaseStrategy.sol | 9 +++++++ src/libraries/TokenizedStrategyLib.sol | 21 ++++++++++++++++ src/test/TokenizedStrategyLibViews.t.sol | 32 ++++++++++++++++++++++++ src/test/mocks/MockStrategy.sol | 19 ++++++++++++++ 5 files changed, 82 insertions(+), 2 deletions(-) diff --git a/foundry.toml b/foundry.toml index 2ebf4b4..18a7445 100644 --- a/foundry.toml +++ b/foundry.toml @@ -6,7 +6,6 @@ solc = "0.8.18" evm_version = "paris" optimize = true optimizer_runs = 200 -no_match_test = "testFail" remappings = [ 'forge-std/=lib/forge-std/src/', @@ -15,7 +14,7 @@ remappings = [ fs_permissions = [{ access = "read", path = "./"}] [fuzz] -runs = 10_0 +runs = 10_000 max_test_rejects = 1_000_000 [invariant] diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 7b3244c..aada4a0 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -73,6 +73,15 @@ abstract contract BaseStrategy { _; } + /** + * @dev Reuses the TokenizedStrategy reentrancy guard for custom strategy functions. + */ + modifier nonReentrant() { + TokenizedStrategy.nonReentrantBefore(); + _; + TokenizedStrategy.nonReentrantAfter(); + } + /** * @dev Require that the msg.sender is this address. */ diff --git a/src/libraries/TokenizedStrategyLib.sol b/src/libraries/TokenizedStrategyLib.sol index ef0d2a6..1e91b6f 100644 --- a/src/libraries/TokenizedStrategyLib.sol +++ b/src/libraries/TokenizedStrategyLib.sol @@ -9,6 +9,9 @@ library TokenizedStrategyLib { bytes32 internal constant BASE_STRATEGY_STORAGE = bytes32(uint256(keccak256("yearn.base.strategy.storage")) - 1); + uint8 internal constant ENTERED = 2; + uint8 internal constant NOT_ENTERED = 1; + // prettier-ignore struct StrategyData { ERC20 asset; @@ -131,6 +134,24 @@ library TokenizedStrategyLib { return strategyStorage().paused; } + function isEntered() internal view returns (bool) { + return strategyStorage().entered == ENTERED; + } + + function nonReentrantBefore() internal { + StrategyData storage S = strategyStorage(); + // On the first call to nonReentrant, `entered` will be false (2) + require(S.entered != ENTERED, "ReentrancyGuard: reentrant call"); + + // Any calls to nonReentrant after this point will fail + S.entered = ENTERED; + } + + function nonReentrantAfter() internal { + // Reset to false (1) once call has finished. + strategyStorage().entered = NOT_ENTERED; + } + function totalAssets() internal view returns (uint256) { return ITokenizedStrategy(address(this)).totalAssets(); } diff --git a/src/test/TokenizedStrategyLibViews.t.sol b/src/test/TokenizedStrategyLibViews.t.sol index f90cee0..2f2a6bf 100644 --- a/src/test/TokenizedStrategyLibViews.t.sol +++ b/src/test/TokenizedStrategyLibViews.t.sol @@ -67,6 +67,38 @@ contract TokenizedStrategyLibViewsTest is Setup { _assertAuthHelpersMatch(newKeeper, newEmergencyAdmin); } + function test_tokenizedStrategyLibraryExposesSharedReentrancyState() + public + { + address owner = address(0xA11CE); + uint256 amount = 100_000 * wad; + + assertFalse(libraryStrategy.libraryIsEntered(), "initial isEntered"); + + libraryStrategy.useBaseReentrancyGuard(); + + assertTrue(libraryStrategy.lastBaseGuardIsEntered(), "base isEntered"); + assertFalse(libraryStrategy.libraryIsEntered(), "base final isEntered"); + + mintAndDepositIntoStrategy(strategy, owner, amount); + + assertTrue( + libraryStrategy.lastDeployFundsIsEntered(), + "hook isEntered" + ); + assertFalse(libraryStrategy.libraryIsEntered(), "hook final isEntered"); + + libraryStrategy.setCallBaseGuardDuringDeploy(true); + + asset.mint(owner, amount); + vm.prank(owner); + asset.approve(address(strategy), amount); + + vm.expectRevert("ReentrancyGuard: reentrant call"); + vm.prank(owner); + strategy.deposit(amount, owner); + } + function _assertAllViewsMatch( address owner, address spender, diff --git a/src/test/mocks/MockStrategy.sol b/src/test/mocks/MockStrategy.sol index 8b6b763..0387b22 100644 --- a/src/test/mocks/MockStrategy.sol +++ b/src/test/mocks/MockStrategy.sol @@ -10,6 +10,9 @@ contract MockStrategy is BaseStrategy { bool public managed; bool public kept; bool public emergentizated; + bool public callBaseGuardDuringDeploy; + bool public lastDeployFundsIsEntered; + bool public lastBaseGuardIsEntered; constructor( address _asset, @@ -25,6 +28,10 @@ contract MockStrategy is BaseStrategy { } function _deployFunds(uint256 _amount) internal override { + lastDeployFundsIsEntered = TokenizedStrategy.isEntered(); + if (callBaseGuardDuringDeploy) { + this.useBaseReentrancyGuard(); + } MockYieldSource(yieldSource).deposit(_amount); } @@ -78,6 +85,14 @@ contract MockStrategy is BaseStrategy { emergentizated = true; } + function setCallBaseGuardDuringDeploy(bool _call) external { + callBaseGuardDuringDeploy = _call; + } + + function useBaseReentrancyGuard() external nonReentrant { + lastBaseGuardIsEntered = TokenizedStrategy.isEntered(); + } + function libraryAsset() external view returns (address) { return TokenizedStrategy.asset(); } @@ -162,6 +177,10 @@ contract MockStrategy is BaseStrategy { return TokenizedStrategy.isPaused(); } + function libraryIsEntered() external view returns (bool) { + return TokenizedStrategy.isEntered(); + } + function libraryTotalAssets() external view returns (uint256) { return TokenizedStrategy.totalAssets(); } From 5de1a435899a83bec1502da513c908c75abc95b2 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Mon, 8 Jun 2026 10:11:20 -0600 Subject: [PATCH 22/27] fix: ignore test fail --- foundry.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/foundry.toml b/foundry.toml index 18a7445..3e9f50e 100644 --- a/foundry.toml +++ b/foundry.toml @@ -6,6 +6,7 @@ solc = "0.8.18" evm_version = "paris" optimize = true optimizer_runs = 200 +no_match_test = "testFail" remappings = [ 'forge-std/=lib/forge-std/src/', From 11a423adaab91f0f925e120fda6a4287f9e6d343 Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Fri, 12 Jun 2026 11:30:29 -0600 Subject: [PATCH 23/27] fix: audit changes (#120) * fix: documentation * fix: first deposit --- SPECIFICATION.md | 13 +- src/BaseStrategy.sol | 29 +++-- src/TokenizedStrategy.sol | 95 +++++++++++---- src/test/Accounting.t.sol | 155 ++++++++++++++++++++++++ src/test/ConstantAccrualInvariant.t.sol | 3 - src/test/utils/Setup.sol | 5 + 6 files changed, 263 insertions(+), 37 deletions(-) diff --git a/SPECIFICATION.md b/SPECIFICATION.md index 0de3873..b9f4662 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -62,7 +62,7 @@ The majority of functions in the BaseStrategy are either external functions with `harvestAndReport()/_harvestAndReport()`: Called during reports to tell the strategy a trusted address has called it and to harvest any rewards re-deploy any loose funds and return the actual amount of funds the strategy holds. -`tendThis(uint256)/_tend(uint256)`: Called by the TokenizedStrategy during tend calls to tell the strategy a trusted address has called tend and it has the uint256 parameter of loose asset available to deposit. NOTE: we use `tendThis` to avoid function signature collisions so that `tend` will be forwarded to the TokenizedStrategy. +`tendThis(uint256)/_tend(uint256)`: Called by the TokenizedStrategy during tend calls to tell the strategy a trusted address has called tend and it has the uint256 parameter of loose asset available to deposit. NOTE: we use `tendThis` to avoid function signature collisions so that `tend` will be forwarded to the TokenizedStrategy. Under constant accrual a tend is not an accounting boundary: value changes it makes price into views through simulated totals and are realized by the next state-changing accrual, not only by a report. `tendTrigger()/_tendTrigger()`: View function to return if a tend call is needed. @@ -86,6 +86,13 @@ Users can deposit ASSET tokens to receive shares. Deposits are limited by the availableDepositLimit function that can be changed by the strategist if non uint256.max values are desired. +#### First Depositor / Donation Protection +Profit recognized by an accrual while the effective share supply is below `MINIMUM_SUPPLY` (1e3) is minted to a dead address as shares at a flat price per share rather than accruing to holders. This covers both assets that show up before the first deposit (the vault starts from a 1:1 PPS) and donations made while an attacker controls a dust supply, which bounds the classic first-depositor inflation attack: for a donation to move the share price at all the attacker must hold at least 1e3 shares of their own, capping any victim rounding loss at roughly `donation / 1e3`. Confiscated profit is not charged performance fees. + +This guard lives only in the accrual path, which is the single point where unsolicited value can enter pricing for permissionless flows (every deposit, mint, withdraw and redeem accrues first, and all conversions price off accrued or simulated totals). `report()` is intentionally not guarded: it is keeper-permissioned, and with a non-zero `profitMaxUnlockTime` profit locking already prevents any instant PPS jump. + +Because no shares are ever carved from depositors, deposits, mints, previews and max functions remain fully ERC-4626 compliant, there is no minimum first deposit, and a vault that is fully exited holds no locked dead shares from normal operation — dead shares only ever result from pre-deposit donations or attacker donations. + #### Withdrawals / Redeems Users can redeem their shares when the strategy is not paused and there is liquidity available. @@ -175,7 +182,7 @@ Once this is called it will stop any further deposit or mints but will have no e This can be used in an emergency or simply to retire a vault. -Once a strategy is shutdown or paused, management or emergencyAdmin can also call `emergencyWithdraw(amount)`. Which will tell the strategy to withdraw a specified `amount` from the yield source and keep it as idle in the vault. This function will also do any needed updates to totalDebt and totalIdle, based on amounts withdrawn to assure withdraws continue to function properly. +Once a strategy is shutdown or paused, management or emergencyAdmin can also call `emergencyWithdraw(amount)`. Which will tell the strategy to withdraw a specified `amount` from the yield source and keep it as idle in the vault. This function performs no accounting update at call time, so the rescue path has no dependency on the strategy's asset estimate. Any profit or loss caused by the unwind prices into views through simulated totals and is realized by the next state-changing accrual or report. All other emergency functionality is left up to the individual strategist. @@ -224,7 +231,7 @@ Strategists should be able to use a pre-built "Strategy Mix" that will contain t While it can be possible to deploy a completely ERC-4626 compliant vault with just those three functions it does allow for further customization if the strategist desires. -*_tend* and *_tendTrigger* can be overridden to signal to keepers the need for any sort of maintenance or reward selling between reports. +*_tend* and *_tendTrigger* can be overridden to signal to keepers the need for any sort of maintenance or reward selling between reports. Note that under constant accrual any value change made during a tend affects view pricing through simulated totals and is realized by the next state-changing accrual rather than waiting for a report. *availableDepositLimit(address _owner)* can be overridden to implement any type of deposit limit. diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index aada4a0..122bd4e 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -254,7 +254,13 @@ abstract contract BaseStrategy { * sandwiched can use the tend when a certain threshold * of idle to totalAssets has been reached. * - * This will have no effect on PPS of the strategy till report() is called. + * NOTE: Under constant accrual this is not an accounting boundary. + * Value changes made here price into {totalAssets}, conversions and + * previews through simulated totals and are realized by the next + * state-changing accrual (any deposit, mint, withdraw, redeem, fee + * configuration change, or report) — not only by report(). Slippage + * or costs incurred here net against any unrealized profit before + * performance fees are charged. * * @param _totalIdle The current amount of idle funds that are available to deploy. */ @@ -295,7 +301,7 @@ abstract contract BaseStrategy { * traditional deposit limit or for implementing a whitelist etc. * * EX: - * if(isAllowed[_owner]) return super.availableDepositLimit(_owner); + * if(isAllowed[receiver]) return super.availableDepositLimit(receiver); * * This does not need to take into account any conversion rates * from shares to assets. But should know that any non max uint256 @@ -303,11 +309,11 @@ abstract contract BaseStrategy { * custom amounts low enough as not to cause overflow when multiplied * by `totalSupply`. * - * @param . The address that is depositing into the strategy. - * @return . The available amount the `_owner` can deposit in terms of `asset` + * @param . The address that is receiving the shares from the deposit. + * @return . The available amount that can be deposited in terms of `asset` */ function availableDepositLimit( - address /*_owner*/ + address /*receiver*/ ) public view virtual returns (uint256) { return type(uint256).max; } @@ -344,11 +350,14 @@ abstract contract BaseStrategy { * This should attempt to free `_amount`, noting that `_amount` may * be more than is currently deployed. * - * NOTE: This will not realize any profits or losses. A separate - * {report} will be needed in order to record any profit/loss. If - * a report may need to be called after a shutdown it is important - * to check if the strategy is shutdown during {_harvestAndReport} - * so that it does not simply re-deploy all funds that had been freed. + * NOTE: Under constant accrual, any profit or loss caused by the + * unwind will be reflected in pricing through simulated totals and + * realized by the next state-changing accrual without further + * action; a {report} is not required but can be used for controlled + * realization. If a report may need to be called after a shutdown it + * is important to check if the strategy is shutdown during + * {_harvestAndReport} so that it does not simply re-deploy all funds + * that had been freed. * * EX: * if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) { diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index a9ce9a0..883a628 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -385,6 +385,9 @@ contract TokenizedStrategy { /// @notice Holder for dead shares minted against unsolicited initial assets. address internal constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD; + /// @notice Supply floor below which accrued profit is minted to + /// {DEAD_ADDRESS} to block first-depositor inflation. + uint256 internal constant MINIMUM_SUPPLY = 1e3; /** * @dev Custom storage slot that will be used to store the @@ -679,6 +682,13 @@ contract TokenizedStrategy { * Normal write flows freeze this value after the first sync in a block. * A manual {report} can refresh it again within that same block. * + * @dev This reflects the *simulated* constant-accrual state, including + * any pending profit or loss that has not yet been realized by a + * state-changing accrual. {convertToShares}, {convertToAssets} and all + * preview functions use the same simulated state, while {totalSupply} + * only reflects realized ERC20 supply. The two views can therefore + * appear inconsistent until the pending accrual is realized. + * * @return . Total assets the strategy holds. */ function totalAssets() external view returns (uint256) { @@ -688,6 +698,14 @@ contract TokenizedStrategy { /** * @notice Get the current supply of the strategies shares. * + * @dev This is the *realized* ERC20 supply (stored supply minus + * unlocked strategy-held shares). It does not include fee shares + * that would be minted for pending constant-accrual profit, nor the + * locked-share burn simulated for pending losses. {totalAssets}, + * conversions and previews do reflect that simulated state, so + * comparing this value against those views may show different + * accounting assumptions until the pending accrual is realized. + * * @return . Total amount of shares outstanding. */ function totalSupply() external view returns (uint256) { @@ -876,7 +894,8 @@ contract TokenizedStrategy { assets = _strategyTotalAssets(); if (S.lastTotalAssets == 0) - return (supply == 0 ? assets : supply, assets); + // Mirrors {_accrue}: supply floor dead mint, fee-free recovery. + return (supply < MINIMUM_SUPPLY ? supply + assets : supply, assets); if (assets > S.lastTotalAssets) { uint256 profit; @@ -884,15 +903,25 @@ contract TokenizedStrategy { profit = assets - S.lastTotalAssets; } - uint16 fee = S.performanceFee; - if (fee != 0 && supply != 0) { - uint256 totalFees = (profit * fee) / MAX_BPS; + if (supply < MINIMUM_SUPPLY) { + // Mirrors the {_accrue} supply floor confiscation. supply += _convertToSharesFromTotals( - totalFees, + profit, supply, - assets - totalFees, - Math.Rounding.Down + S.lastTotalAssets, + Math.Rounding.Up ); + } else { + uint16 fee = S.performanceFee; + if (fee != 0) { + uint256 totalFees = (profit * fee) / MAX_BPS; + supply += _convertToSharesFromTotals( + totalFees, + supply, + assets - totalFees, + Math.Rounding.Down + ); + } } } else if (assets < S.lastTotalAssets) { uint256 loss; @@ -1177,14 +1206,25 @@ contract TokenizedStrategy { profit = newTotalAssets - oldTotalAssets; } - // Any assets that show up before the first depositor should not be - // claimable by that first depositor. Mint matching dead shares so - // the vault starts from a 1:1 PPS. - if (oldTotalAssets == 0 && S.totalSupply == 0) { - _mint(S, DEAD_ADDRESS, newTotalAssets); - } - - if (oldTotalAssets != 0) { + // Profit accrued below the supply floor is confiscated to dead + // shares at a flat PPS, fee free, so a dust supply can never + // capture a donation. + uint256 supply = _totalSupply(S); + if (supply < MINIMUM_SUPPLY) { + _mint( + S, + DEAD_ADDRESS, + // If there is no prior PPS to preserve, target 1:1. + oldTotalAssets == 0 + ? newTotalAssets + : _convertToSharesFromTotals( + profit, + supply, + oldTotalAssets, + Math.Rounding.Up + ) + ); + } else if (oldTotalAssets != 0) { (totalFees, protocolFees, ) = _chargeFees( S, profit, @@ -1374,7 +1414,7 @@ contract TokenizedStrategy { uint256 newTotalAssets = IBaseStrategy(address(this)) .harvestAndReport(); - uint256 oldTotalAssets = _totalAssets(S); + uint256 oldTotalAssets = S.lastTotalAssets; // Initialize variables needed throughout. uint256 totalFees; @@ -1521,10 +1561,18 @@ contract TokenizedStrategy { * be used for illiquid or manipulatable strategies to compound * rewards, perform maintenance or deposit/withdraw funds. * - * This will not cause any change in PPS. Total assets will - * be the same before and after. + * This performs no accounting checkpoint itself. Under constant + * accrual, any value change made by '_tend' is reflected in + * {totalAssets}, conversions and previews through simulation — + * immediately within this block if no accrual has latched it yet + * (see {totalAssets}), otherwise from the next block — and is + * realized (fees charged, losses offset) by the next state-changing + * accrual: any deposit, mint, withdraw, redeem, fee configuration + * change, or report. * - * A report() call will be needed to record any profits or losses. + * Any pre-existing pending profit or loss nets against the effects + * of the tend before fees are assessed. This is intended: performance + * fees are charged on the net result, not the gross. */ function tend() external nonReentrant onlyKeepers { // Tend the strategy with the current loose balance. @@ -1580,8 +1628,13 @@ contract TokenizedStrategy { * strategy has been shutdown. * @dev This can only be called when the strategy is paused or shutdown. * - * This will never cause a change in PPS. Total assets will - * be the same before and after. + * This path deliberately performs no accrual so that the rescue flow + * has no dependency on `strategyTotalAssets()`, which may revert or + * be unreliable mid-emergency. Any profit or loss caused by the + * unwind follows the same rules as {tend}: it is reflected in + * {totalAssets}, conversions and previews through simulation and is + * realized by the next state-changing accrual. Management can call + * {report} afterward if controlled realization is desired. * * A strategist will need to override the {_emergencyWithdraw} function * in their strategy for this to work. diff --git a/src/test/Accounting.t.sol b/src/test/Accounting.t.sol index cfc2561..2381c52 100644 --- a/src/test/Accounting.t.sol +++ b/src/test/Accounting.t.sol @@ -426,6 +426,161 @@ contract AccountingTest is Setup { assertEq(strategy.totalAssets(), _donation, "!remaining"); } + /// @dev 1 wei seed + donation: the floor confiscates the donation so + /// the victim deposits at ~1:1. + function test_accrualFloor_oneWeiSeedAttackConfiscated() public { + setFees(0, 1_000); + address attacker = address(0xA11CE); + address victim = address(0xB0B); + + // No minimum first deposit: 1 wei mints 1 share. + asset.mint(attacker, 1); + vm.startPrank(attacker); + asset.approve(address(strategy), 1); + strategy.deposit(1, attacker); + vm.stopPrank(); + assertEq(strategy.balanceOf(attacker), 1, "!seed"); + + uint256 donation = 100e18; + asset.mint(attacker, donation); + vm.prank(attacker); + asset.transfer(address(strategy), donation); + skip(1); + + uint256 victimDeposit = 200e18; + mintAndDepositIntoStrategy(strategy, victim, victimDeposit); + + // The donation was minted to dead shares at a flat PPS. + assertEq(strategy.balanceOf(DEAD_ADDRESS), donation, "!dead"); + assertEq(strategy.balanceOf(victim), victimDeposit, "!victim shares"); + assertApproxEqAbs( + strategy.convertToAssets(strategy.balanceOf(victim)), + victimDeposit, + 2, + "!victim value" + ); + + // No performance fees were charged on the confiscated profit. + assertEq(strategy.balanceOf(performanceFeeRecipient), 0, "!fee shares"); + + // The attacker's share is back to ~1 wei: the donation is lost. + assertLe( + strategy.convertToAssets(strategy.balanceOf(attacker)), + 1, + "!attacker value" + ); + } + + /// @dev At or above the floor a donation accrues, but victim rounding + /// loss is bounded by ~donation / MINIMUM_SUPPLY. + function test_accrualFloor_supplyAboveFloorBoundsAttack() public { + setFees(0, 1_000); + address attacker = address(0xA11CE); + address victim = address(0xB0B); + + uint256 seed = MINIMUM_SUPPLY; + asset.mint(attacker, seed); + vm.startPrank(attacker); + asset.approve(address(strategy), seed); + strategy.deposit(seed, attacker); + vm.stopPrank(); + + uint256 donation = 100e18; + asset.mint(attacker, donation); + vm.prank(attacker); + asset.transfer(address(strategy), donation); + skip(1); + + uint256 victimDeposit = 200e18; + mintAndDepositIntoStrategy(strategy, victim, victimDeposit); + + // Supply was at the floor: nothing was confiscated. + assertEq(strategy.balanceOf(DEAD_ADDRESS), 0, "!dead"); + + // Victim rounding loss is bounded by ~donation / MINIMUM_SUPPLY. + assertGe( + strategy.convertToAssets(strategy.balanceOf(victim)), + victimDeposit - donation / MINIMUM_SUPPLY - 1, + "!victim bound" + ); + + // The attacker ends up underwater versus seed + donation. + assertLt( + strategy.convertToAssets(strategy.balanceOf(attacker)), + seed + donation, + "!attacker not profitable" + ); + } + + /// @dev Full deposit/profit/exit cycles never mint dead shares. + function test_accrualFloor_fullCycleLeavesNoDeadShares( + address _user, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _user != address(0) && + _user != address(strategy) && + _user != address(yieldSource) && + _user != DEAD_ADDRESS + ); + + setFees(0, 0); + + for (uint256 i; i < 2; ++i) { + mintAndDepositIntoStrategy(strategy, _user, _amount); + + // Earn and report a real profit, then let it fully unlock. + uint256 profit = _amount / 10; + asset.mint(address(yieldSource), profit); + skip(1); + vm.prank(keeper); + strategy.report(); + skip(profitMaxUnlockTime); + + uint256 shares = strategy.balanceOf(_user); + vm.prank(_user); + strategy.redeem(shares, _user, _user); + + // Fully emptied: no value stuck in dead shares. + assertEq(strategy.balanceOf(DEAD_ADDRESS), 0, "!dead"); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + } + + /// @dev Views simulate the dead mint: previews match actual deposits. + function test_accrualFloor_viewsMatchWritePath() public { + setFees(0, 1_000); + address seeder = address(0xA11CE); + address depositor = address(0xB0B); + + uint256 seed = 10; + asset.mint(seeder, seed); + vm.startPrank(seeder); + asset.approve(address(strategy), seed); + strategy.deposit(seed, seeder); + vm.stopPrank(); + + // Pending profit against a dust supply. + asset.mint(address(strategy), 1e18); + skip(1); + + uint256 amount = 5e18; + uint256 preview = strategy.previewDeposit(amount); + assertEq(preview, strategy.convertToShares(amount), "!convert"); + // Flat PPS: the simulated dead mint keeps the price at 1:1. + assertEq(preview, amount, "!flat pps"); + + asset.mint(depositor, amount); + vm.startPrank(depositor); + asset.approve(address(strategy), amount); + uint256 minted = strategy.deposit(amount, depositor); + vm.stopPrank(); + + assertEq(minted, preview, "!preview matches"); + assertEq(strategy.balanceOf(depositor), minted, "!return matches"); + } + function test_zeroAssetRecoveryIsFeeFreeAndPreviewMatchesDeposit() public { address depositor = address(0xA11CE); address recoveryDepositor = address(0xB0B); diff --git a/src/test/ConstantAccrualInvariant.t.sol b/src/test/ConstantAccrualInvariant.t.sol index 8d3dc64..844d8f7 100644 --- a/src/test/ConstantAccrualInvariant.t.sol +++ b/src/test/ConstantAccrualInvariant.t.sol @@ -5,9 +5,6 @@ import {BaseInvariant} from "./utils/BaseInvariant.sol"; import {ConstantAccrualHandler} from "./handlers/ConstantAccrualHandler.sol"; contract ConstantAccrualInvariantTest is BaseInvariant { - address internal constant DEAD_ADDRESS = - 0x000000000000000000000000000000000000dEaD; - ConstantAccrualHandler public constantAccrualHandler; function setUp() public override { diff --git a/src/test/utils/Setup.sol b/src/test/utils/Setup.sol index eeead06..8aa6e82 100644 --- a/src/test/utils/Setup.sol +++ b/src/test/utils/Setup.sol @@ -32,6 +32,11 @@ contract Setup is ExtendedTest, IEvents { address public protocolFeeRecipient = address(5); address public performanceFeeRecipient = address(6); + // Recipient of shares minted against profit accrued below the supply floor. + address public constant DEAD_ADDRESS = + 0x000000000000000000000000000000000000dEaD; + uint256 public constant MINIMUM_SUPPLY = 1e3; + // Integer variables that will be used repeatedly. uint256 public decimals = 18; uint256 public MAX_BPS = 10_000; From 476843022fe31019c20f3a11063294a4a545e387 Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Fri, 12 Jun 2026 12:12:47 -0600 Subject: [PATCH 24/27] 310 fixes (#119) * fix: naming * fix: reentrancy name --- src/BaseStrategy.sol | 10 +++++----- src/test/AccessControl.t.sol | 4 ++-- src/test/mocks/MockFaultyStrategy.sol | 4 ++-- src/test/mocks/MockIlliquidStrategy.sol | 4 ++-- src/test/mocks/MockStrategy.sol | 6 +++--- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 122bd4e..461455d 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -22,7 +22,7 @@ import {TokenizedStrategyLib as TokenizedStrategy} from "./libraries/TokenizedSt * can only be concerned with writing their strategy specific code. * * This contract should be inherited and the three main abstract methods - * `_deployFunds`, `_freeFunds` and `_totalAssets` implemented to adapt + * `_deployFunds`, `_freeFunds` and `_strategyTotalAssets` implemented to adapt * the Strategy to the particular needs it has to generate yield. There are * other optional methods that can be implemented to further customize * the strategy if desired. @@ -76,7 +76,7 @@ abstract contract BaseStrategy { /** * @dev Reuses the TokenizedStrategy reentrancy guard for custom strategy functions. */ - modifier nonReentrant() { + modifier nonReentrantTokenized() { TokenizedStrategy.nonReentrantBefore(); _; TokenizedStrategy.nonReentrantAfter(); @@ -213,10 +213,10 @@ abstract contract BaseStrategy { * when they refresh. It must be strictly read only and should not harvest, * claim or otherwise mutate state. * - * @return _totalAssets A trusted and accurate account for the total + * @return _strategyTotalAssets A trusted and accurate account for the total * amount of 'asset' the strategy currently holds including idle funds. */ - function _totalAssets() internal view virtual returns (uint256); + function _strategyTotalAssets() internal view virtual returns (uint256); /** * @dev Internal hook used by explicit {report()} accounting syncs. @@ -395,7 +395,7 @@ abstract contract BaseStrategy { * @dev Read-only callback for the TokenizedStrategy. */ function strategyTotalAssets() external view virtual returns (uint256) { - return _totalAssets(); + return _strategyTotalAssets(); } /** diff --git a/src/test/AccessControl.t.sol b/src/test/AccessControl.t.sol index 33646db..d971300 100644 --- a/src/test/AccessControl.t.sol +++ b/src/test/AccessControl.t.sol @@ -41,12 +41,12 @@ contract CustomInitMockStrategy is BaseStrategy { function _freeFunds(uint256) internal override {} - function _totalAssets() internal view override returns (uint256) { + function _strategyTotalAssets() internal view override returns (uint256) { return asset.balanceOf(address(this)); } function _harvestAndReport() internal override returns (uint256) { - return _totalAssets(); + return _strategyTotalAssets(); } } diff --git a/src/test/mocks/MockFaultyStrategy.sol b/src/test/mocks/MockFaultyStrategy.sol index a17f7f6..11d6ba9 100644 --- a/src/test/mocks/MockFaultyStrategy.sol +++ b/src/test/mocks/MockFaultyStrategy.sol @@ -40,7 +40,7 @@ contract MockFaultyStrategy is BaseStrategy { MockYieldSource(yieldSource).withdraw(_amount + fault); } - function _totalAssets() internal view override returns (uint256) { + function _strategyTotalAssets() internal view override returns (uint256) { return MockYieldSource(yieldSource).balance() + ERC20(asset).balanceOf(address(this)); @@ -54,7 +54,7 @@ contract MockFaultyStrategy is BaseStrategy { // Write paths now sync through harvest before user actions. Keep this // mock focused on deploy/free/tend callbacks so the reentrancy tests // still isolate the path they are named after. - return _totalAssets(); + return _strategyTotalAssets(); } function _tend(uint256 _idle) internal override { diff --git a/src/test/mocks/MockIlliquidStrategy.sol b/src/test/mocks/MockIlliquidStrategy.sol index fc10195..78ce483 100644 --- a/src/test/mocks/MockIlliquidStrategy.sol +++ b/src/test/mocks/MockIlliquidStrategy.sol @@ -25,7 +25,7 @@ contract MockIlliquidStrategy is BaseStrategy { //MockYieldSource(yieldSource).withdraw(_amount); } - function _totalAssets() internal view override returns (uint256) { + function _strategyTotalAssets() internal view override returns (uint256) { return MockYieldSource(yieldSource).balance() + ERC20(asset).balanceOf(address(this)); @@ -34,7 +34,7 @@ contract MockIlliquidStrategy is BaseStrategy { function _harvestAndReport() internal view override returns (uint256) { // Live write-path syncing now runs before user withdraw/redeem flows. // Keep this mock's withdrawal limit stable by not moving idle funds here. - return _totalAssets(); + return _strategyTotalAssets(); } function _tend(uint256 /*_idle*/) internal override { diff --git a/src/test/mocks/MockStrategy.sol b/src/test/mocks/MockStrategy.sol index 0387b22..ccc7911 100644 --- a/src/test/mocks/MockStrategy.sol +++ b/src/test/mocks/MockStrategy.sol @@ -39,7 +39,7 @@ contract MockStrategy is BaseStrategy { MockYieldSource(yieldSource).withdraw(_amount); } - function _totalAssets() internal view override returns (uint256) { + function _strategyTotalAssets() internal view override returns (uint256) { return MockYieldSource(yieldSource).balance() + ERC20(asset).balanceOf(address(this)); @@ -51,7 +51,7 @@ contract MockStrategy is BaseStrategy { if (balance > 0 && !TokenizedStrategy.isShutdown()) { MockYieldSource(yieldSource).deposit(balance); } - return _totalAssets(); + return _strategyTotalAssets(); } function _tend(uint256 /*_idle*/) internal override { @@ -89,7 +89,7 @@ contract MockStrategy is BaseStrategy { callBaseGuardDuringDeploy = _call; } - function useBaseReentrancyGuard() external nonReentrant { + function useBaseReentrancyGuard() external nonReentrantTokenized { lastBaseGuardIsEntered = TokenizedStrategy.isEntered(); } From 48541220149ff5628271092c7b931a4c92697515 Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Thu, 18 Jun 2026 13:46:30 -0600 Subject: [PATCH 25/27] chore: add default total assets (#121) * fix: naming * fix: reentrancy name * chore: read me * test: default behaviour * fix: ascii --- README.md | 4 +- SPECIFICATION.md | 10 +- src/BaseStrategy.sol | 80 +-- src/TokenizedStrategy.sol | 14 +- src/test/LegacyAccounting.t.sol | 740 ++++++++++++++++++++++++++ src/test/mocks/LegacyMockStrategy.sol | 140 +++++ src/test/mocks/MockStorage.sol | 78 ++- src/test/utils/Setup.sol | 4 +- 8 files changed, 979 insertions(+), 91 deletions(-) create mode 100644 src/test/LegacyAccounting.t.sol create mode 100644 src/test/mocks/LegacyMockStrategy.sol diff --git a/README.md b/README.md index 0ffe49e..c7e46f7 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +> [!CAUTION] +> **v3.1.0 risk:** share pricing is driven by `strategyTotalAssets()`. The default returns `lastTotalAssets()`, but strategies that override it for live accounting can move PPS, previews, and conversions before `report()`; if that value is wrong or manipulable, vault shares can be mispriced. # Yearn Tokenized Strategy @@ -7,7 +9,7 @@ The implementation address that calls are delegated to is pre-set to a constant NOTE: The master branch has these pre-set addresses set based on the deterministic address that testing on a local device will render. These contracts should NOT be used in production and any live versions should use an official [release](https://github.com/yearn/tokenized-strategy/releases). -A Strategy contract can become a fully ERC-4626 compliant vault by inheriting the `BaseStrategy` contract, that uses the fallback function to delegateCall the previously deployed version of `TokenizedStrategy`. A strategist then only needs to override three simple functions in their specific strategy. +A Strategy contract can become a fully ERC-4626 compliant vault by inheriting the `BaseStrategy` contract, that uses the fallback function to delegateCall the previously deployed version of `TokenizedStrategy`. A strategist then only needs to override three required functions in their specific strategy, with the option to override `_strategyTotalAssets()` for live accounting. [TokenizedStrategy](https://github.com/yearn/tokenized-strategy/blob/master/src/TokenizedStrategy.sol) - The implementation contract that holds all logic for every strategy. diff --git a/SPECIFICATION.md b/SPECIFICATION.md index b9f4662..229f6db 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -62,7 +62,7 @@ The majority of functions in the BaseStrategy are either external functions with `harvestAndReport()/_harvestAndReport()`: Called during reports to tell the strategy a trusted address has called it and to harvest any rewards re-deploy any loose funds and return the actual amount of funds the strategy holds. -`tendThis(uint256)/_tend(uint256)`: Called by the TokenizedStrategy during tend calls to tell the strategy a trusted address has called tend and it has the uint256 parameter of loose asset available to deposit. NOTE: we use `tendThis` to avoid function signature collisions so that `tend` will be forwarded to the TokenizedStrategy. Under constant accrual a tend is not an accounting boundary: value changes it makes price into views through simulated totals and are realized by the next state-changing accrual, not only by a report. +`tendThis(uint256)/_tend(uint256)`: Called by the TokenizedStrategy during tend calls to tell the strategy a trusted address has called tend and it has the uint256 parameter of loose asset available to deposit. NOTE: we use `tendThis` to avoid function signature collisions so that `tend` will be forwarded to the TokenizedStrategy. If `_strategyTotalAssets()` is overridden for constant accrual, a tend is not an accounting boundary: value changes it makes price into views through simulated totals and are realized by the next state-changing accrual, not only by a report. `tendTrigger()/_tendTrigger()`: View function to return if a tend call is needed. @@ -191,7 +191,7 @@ Withdrawals and redemptions are paused by `setPaused(true)`, which can be called ## Use -A strategist can simply inherit the BaseStrategy.sol contract and override 3 simple functions with their specific needs. +A strategist can simply inherit the BaseStrategy.sol contract and override 3 required functions with their specific needs. They can also override `_strategyTotalAssets()` if they want live accounting instead of the default report-boundary accounting. The strategies code has been designed as a non-opinionated system to distribute funds of depositors to a single yield generating opportunity while managing accounting in a robust way. @@ -216,7 +216,7 @@ Example constraints: - ... ## Development -Strategists should be able to use a pre-built "Strategy Mix" that will contain the imported BaseStrategy.sol as well as standardized tests for any 4626 vault. Developing a strategy can be as simple as overriding three functions, with the potential for any number of other constraints or actions to be built on top of it. The Base implementation is only ~2KB, meaning there is plenty of room for strategists to build complex implementations while not having to be concerned with the generic functionality. +Strategists should be able to use a pre-built "Strategy Mix" that will contain the imported BaseStrategy.sol as well as standardized tests for any 4626 vault. Developing a strategy can be as simple as overriding three required functions, with the potential for any number of other constraints or actions to be built on top of it. The Base implementation is only ~2KB, meaning there is plenty of room for strategists to build complex implementations while not having to be concerned with the generic functionality. ### Needed to Override @@ -231,7 +231,9 @@ Strategists should be able to use a pre-built "Strategy Mix" that will contain t While it can be possible to deploy a completely ERC-4626 compliant vault with just those three functions it does allow for further customization if the strategist desires. -*_tend* and *_tendTrigger* can be overridden to signal to keepers the need for any sort of maintenance or reward selling between reports. Note that under constant accrual any value change made during a tend affects view pricing through simulated totals and is realized by the next state-changing accrual rather than waiting for a report. +*_strategyTotalAssets()*: By default this returns `TokenizedStrategy.lastTotalAssets()`, preserving report-boundary accounting. Override it only when the strategy needs live accounting from a read-only current asset estimate. + +*_tend* and *_tendTrigger* can be overridden to signal to keepers the need for any sort of maintenance or reward selling between reports. If `_strategyTotalAssets()` is overridden for constant accrual, any value change made during a tend affects view pricing through simulated totals and is realized by the next state-changing accrual rather than waiting for a report. *availableDepositLimit(address _owner)* can be overridden to implement any type of deposit limit. diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index 461455d..e201082 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -13,8 +13,8 @@ import {TokenizedStrategyLib as TokenizedStrategy} from "./libraries/TokenizedSt * BaseStrategy implements all of the required functionality to * seamlessly integrate with the `TokenizedStrategy` implementation contract * allowing anyone to easily build a fully permissionless ERC-4626 compliant - * Vault by inheriting this contract and overriding three simple functions. - + * Vault by inheriting this contract and overriding three required functions. + * * It utilizes an immutable proxy pattern that allows the BaseStrategy * to remain simple and small. All standard logic is held within the * `TokenizedStrategy` and is reused over any n strategies all using the @@ -22,10 +22,10 @@ import {TokenizedStrategyLib as TokenizedStrategy} from "./libraries/TokenizedSt * can only be concerned with writing their strategy specific code. * * This contract should be inherited and the three main abstract methods - * `_deployFunds`, `_freeFunds` and `_strategyTotalAssets` implemented to adapt - * the Strategy to the particular needs it has to generate yield. There are - * other optional methods that can be implemented to further customize - * the strategy if desired. + * `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt + * the Strategy to the particular needs it has to generate yield. Optional + * methods, including `_strategyTotalAssets`, can be implemented to further + * customize the strategy if desired. * * All default storage for the strategy is controlled and updated by the * `TokenizedStrategy`. The implementation holds a storage struct that @@ -76,6 +76,7 @@ abstract contract BaseStrategy { /** * @dev Reuses the TokenizedStrategy reentrancy guard for custom strategy functions. */ + modifier nonReentrantTokenized() { TokenizedStrategy.nonReentrantBefore(); _; @@ -201,23 +202,6 @@ abstract contract BaseStrategy { */ function _freeFunds(uint256 _amount) internal virtual; - /** - * @dev Internal function to return an accurate accounting of all funds - * currently held by the Strategy. - * - * NOTE: All applicable assets including loose assets should be - * accounted for in this function. - * - * This function is used by ERC4626 view methods whenever the current block - * is not already latched, and by normal state changing accounting syncs - * when they refresh. It must be strictly read only and should not harvest, - * claim or otherwise mutate state. - * - * @return _strategyTotalAssets A trusted and accurate account for the total - * amount of 'asset' the strategy currently holds including idle funds. - */ - function _strategyTotalAssets() internal view virtual returns (uint256); - /** * @dev Internal hook used by explicit {report()} accounting syncs. * @@ -237,6 +221,27 @@ abstract contract BaseStrategy { OPTIONAL TO OVERRIDE BY STRATEGIST //////////////////////////////////////////////////////////////*/ + /** + * @dev Internal function to return the Strategy's current asset estimate. + * + * The default returns the last realized total assets, preserving the + * report-boundary accounting behavior used before live accrual. Strategies + * that want constant accrual should override this with a strictly read-only + * estimate of all assets, including loose funds. + * + * NOTE: An override must not harvest, claim or otherwise mutate state. + * + * @return _totalAssets The strategy's current asset estimate. + */ + function _strategyTotalAssets() + internal + view + virtual + returns (uint256 _totalAssets) + { + return TokenizedStrategy.lastTotalAssets(); + } + /** * @dev Optional function for strategist to override that can * be called in between reports. @@ -254,12 +259,12 @@ abstract contract BaseStrategy { * sandwiched can use the tend when a certain threshold * of idle to totalAssets has been reached. * - * NOTE: Under constant accrual this is not an accounting boundary. - * Value changes made here price into {totalAssets}, conversions and - * previews through simulated totals and are realized by the next - * state-changing accrual (any deposit, mint, withdraw, redeem, fee - * configuration change, or report) — not only by report(). Slippage - * or costs incurred here net against any unrealized profit before + * NOTE: If `_strategyTotalAssets` is overridden for constant accrual, this + * is not an accounting boundary. Value changes made here price into + * {totalAssets}, conversions and previews through simulated totals and are + * realized by the next state-changing accrual (any deposit, mint, withdraw, + * redeem, fee configuration change, or report) — not only by report(). + * Slippage or costs incurred here net against any unrealized profit before * performance fees are charged. * * @param _totalIdle The current amount of idle funds that are available to deploy. @@ -350,14 +355,13 @@ abstract contract BaseStrategy { * This should attempt to free `_amount`, noting that `_amount` may * be more than is currently deployed. * - * NOTE: Under constant accrual, any profit or loss caused by the - * unwind will be reflected in pricing through simulated totals and - * realized by the next state-changing accrual without further - * action; a {report} is not required but can be used for controlled - * realization. If a report may need to be called after a shutdown it - * is important to check if the strategy is shutdown during - * {_harvestAndReport} so that it does not simply re-deploy all funds - * that had been freed. + * NOTE: If `_strategyTotalAssets` is overridden for constant accrual, any + * profit or loss caused by the unwind will be reflected in pricing through + * simulated totals and realized by the next state-changing accrual without + * further action; a {report} is not required but can be used for controlled + * realization. If a report may need to be called after a shutdown it is + * important to check if the strategy is shutdown during {_harvestAndReport} + * so that it does not simply re-deploy all funds that had been freed. * * EX: * if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) { @@ -437,7 +441,7 @@ abstract contract BaseStrategy { * * We name the function `tendThis` so that `tend` calls are forwarded to * the TokenizedStrategy. - + * * @param _totalIdle The amount of current idle funds that can be * deployed during the tend */ diff --git a/src/TokenizedStrategy.sol b/src/TokenizedStrategy.sol index 883a628..2f5f3fd 100644 --- a/src/TokenizedStrategy.sol +++ b/src/TokenizedStrategy.sol @@ -66,7 +66,7 @@ import {IBaseStrategy} from "./interfaces/IBaseStrategy.sol"; * management for a custom strategy that inherits the `BaseStrategy`. * Any function calls to the strategy that are not defined within that * strategy will be forwarded through a delegateCall to this contract. - + * * A strategist only needs to override a few simple functions that are * focused entirely on the strategy specific needs to easily and cheaply * deploy their own permissionless 4626 compliant vault. @@ -224,7 +224,6 @@ contract TokenizedStrategy { // used by the Strategy ERC20 asset; - // These are the corresponding ERC20 variables needed for the // strategies token that is issued and burned on each deposit or withdraw. uint8 decimals; // The amount of decimals that `asset` and strategy use. @@ -888,14 +887,18 @@ contract TokenizedStrategy { ) internal view returns (uint256 supply, uint256 assets) { supply = _totalSupply(S); - if (S.entered == ENTERED || block.timestamp == S.lastAccrual) + if (S.entered == ENTERED || block.timestamp == S.lastAccrual) { return (supply, S.lastTotalAssets); + } assets = _strategyTotalAssets(); - if (S.lastTotalAssets == 0) + if ( + S.lastTotalAssets == 0 // Mirrors {_accrue}: supply floor dead mint, fee-free recovery. + ) { return (supply < MINIMUM_SUPPLY ? supply + assets : supply, assets); + } if (assets > S.lastTotalAssets) { uint256 profit; @@ -2144,7 +2147,8 @@ contract TokenizedStrategy { emit Transfer(from, to, amount); } - /** @dev Creates `amount` tokens and assigns them to `account`, increasing + /** + * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. diff --git a/src/test/LegacyAccounting.t.sol b/src/test/LegacyAccounting.t.sol new file mode 100644 index 0000000..e70a8c4 --- /dev/null +++ b/src/test/LegacyAccounting.t.sol @@ -0,0 +1,740 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity >=0.8.18; + +import "forge-std/console.sol"; +import {IMockStrategy} from "./mocks/IMockStrategy.sol"; +import {LegacyMockIlliquidStrategy, LegacyMockStrategy} from "./mocks/LegacyMockStrategy.sol"; +import {Setup} from "./utils/Setup.sol"; + +contract LegacyAccountingTest is Setup { + function setUp() public override { + super.setUp(); + vm.label(address(strategy), "legacy strategy"); + } + + function setUpStrategy() public override returns (address) { + IMockStrategy _strategy = IMockStrategy( + address( + new LegacyMockStrategy(address(asset), address(yieldSource)) + ) + ); + + _setUpRoles(_strategy); + + return address(_strategy); + } + + function setUpIlliquidStrategy() public override returns (address) { + IMockStrategy _strategy = IMockStrategy( + address( + new LegacyMockIlliquidStrategy( + address(asset), + address(yieldSource) + ) + ) + ); + + _setUpRoles(_strategy); + + return address(_strategy); + } + + function _setUpRoles(IMockStrategy _strategy) internal { + _strategy.setKeeper(keeper); + _strategy.setEmergencyAdmin(emergencyAdmin); + _strategy.setPerformanceFeeRecipient(performanceFeeRecipient); + _strategy.setPendingManagement(management); + + vm.prank(management); + _strategy.acceptManagement(); + } + + function test_airdropDoesNotIncreasePPS( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + // set fees to 0 for calculations simplicity + setFees(0, 0); + + // nothing has happened pps should be 1 + uint256 pricePerShare = strategy.pricePerShare(); + assertEq(pricePerShare, wad); + + // deposit into the vault + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // should still be 1 + assertEq(strategy.pricePerShare(), pricePerShare); + + // airdrop to strategy + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), toAirdrop); + + // PPS shouldn't change but the balance does. + assertEq(strategy.pricePerShare(), pricePerShare); + checkStrategyTotals( + strategy, + _amount, + _amount - toAirdrop, + toAirdrop, + _amount + ); + + uint256 beforeBalance = asset.balanceOf(_address); + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + // should have pulled out just the deposited amount leaving the rest deployed. + assertEq(asset.balanceOf(_address), beforeBalance + _amount); + assertEq(asset.balanceOf(address(strategy)), 0); + assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_airdropDoesNotIncreasePPS_reportRecordsIt( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + // set fees to 0 for calculations simplicity + setFees(0, 0); + + // nothing has happened pps should be 1 + uint256 pricePerShare = strategy.pricePerShare(); + assertEq(pricePerShare, wad); + + // deposit into the vault + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // should still be 1 + assertEq(strategy.pricePerShare(), pricePerShare); + + // airdrop to strategy + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), toAirdrop); + + // PPS shouldn't change but the balance does. + assertEq(strategy.pricePerShare(), pricePerShare); + checkStrategyTotals( + strategy, + _amount, + _amount - toAirdrop, + toAirdrop, + _amount + ); + + // process a report to realize the gain from the airdrop + uint256 profit; + vm.prank(keeper); + (profit, ) = strategy.report(); + + assertEq(strategy.pricePerShare(), pricePerShare); + assertEq(profit, toAirdrop); + checkStrategyTotals( + strategy, + _amount + toAirdrop, + _amount + toAirdrop, + 0, + _amount + toAirdrop + ); + + // allow some profit to come unlocked + skip(profitMaxUnlockTime / 2); + + assertGt(strategy.pricePerShare(), pricePerShare); + + //air drop again, we should not increase again + pricePerShare = strategy.pricePerShare(); + asset.mint(address(strategy), toAirdrop); + assertEq(strategy.pricePerShare(), pricePerShare); + + // skip the rest of the time for unlocking + skip(profitMaxUnlockTime / 2); + + // we should get a % return equal to our profit factor + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + // Total is the same but balance has adjusted again + checkStrategyTotals(strategy, _amount + toAirdrop, _amount, toAirdrop); + + uint256 beforeBalance = asset.balanceOf(_address); + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + // should have pulled out the deposit plus profit that was reported but not the second airdrop + assertEq( + asset.balanceOf(_address), + beforeBalance + _amount + toAirdrop + ); + assertEq(asset.balanceOf(address(strategy)), 0); + assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_earningYieldDoesNotIncreasePPS( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + // set fees to 0 for calculations simplicity + setFees(0, 0); + + // nothing has happened pps should be 1 + uint256 pricePerShare = strategy.pricePerShare(); + assertEq(pricePerShare, wad); + + // deposit into the strategy + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // should still be 1 + assertEq(strategy.pricePerShare(), pricePerShare); + + // airdrop to strategy + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(yieldSource), toAirdrop); + + // nothing should change + assertEq(strategy.pricePerShare(), pricePerShare); + checkStrategyTotals(strategy, _amount, _amount, 0, _amount); + + uint256 beforeBalance = asset.balanceOf(_address); + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + // should have pulled out just the deposit amount + assertEq(asset.balanceOf(_address), beforeBalance + _amount); + assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_earningYieldDoesNotIncreasePPS_reportRecordsIt( + address _address, + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + // set fees to 0 for calculations simplicity + setFees(0, 0); + + // nothing has happened pps should be 1 + uint256 pricePerShare = strategy.pricePerShare(); + assertEq(pricePerShare, wad); + + // deposit into the vault + mintAndDepositIntoStrategy(strategy, _address, _amount); + + // should still be 1 + assertEq(strategy.pricePerShare(), pricePerShare); + + // airdrop to strategy + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(yieldSource), toAirdrop); + assertEq(asset.balanceOf(address(yieldSource)), _amount + toAirdrop); + + // nothing should change + assertEq(strategy.pricePerShare(), pricePerShare); + checkStrategyTotals(strategy, _amount, _amount, 0, _amount); + + // process a report to realize the gain from the airdrop + uint256 profit; + vm.prank(keeper); + (profit, ) = strategy.report(); + + assertEq(strategy.pricePerShare(), pricePerShare); + assertEq(profit, toAirdrop); + + checkStrategyTotals( + strategy, + _amount + toAirdrop, + _amount + toAirdrop, + 0, + _amount + toAirdrop + ); + + // allow some profit to come unlocked + skip(profitMaxUnlockTime / 2); + + assertGt(strategy.pricePerShare(), pricePerShare); + + //air drop again, we should not increase again + pricePerShare = strategy.pricePerShare(); + asset.mint(address(yieldSource), toAirdrop); + assertEq(strategy.pricePerShare(), pricePerShare); + + // skip the rest of the time for unlocking + skip(profitMaxUnlockTime / 2); + + // we should get a % return equal to our profit factor + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + // Total is the same. + checkStrategyTotals( + strategy, + _amount + toAirdrop, + _amount + toAirdrop, + 0 + ); + + uint256 beforeBalance = asset.balanceOf(_address); + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + // should have pulled out the deposit plus profit that was reported but not the second airdrop + assertEq( + asset.balanceOf(_address), + beforeBalance + _amount + toAirdrop + ); + + assertEq(asset.balanceOf(address(yieldSource)), toAirdrop); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_tend_noIdle_harvestProfit( + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 1, MAX_BPS)); + + setFees(0, 0); + // nothing has happened pps should be 1 + uint256 pricePerShare = strategy.pricePerShare(); + assertEq(pricePerShare, wad); + + // deposit into the vault + mintAndDepositIntoStrategy(strategy, user, _amount); + + // should still be 1 + assertEq(strategy.pricePerShare(), pricePerShare); + + // airdrop to strategy to simulate a harvesting of rewards + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), toAirdrop); + assertEq(asset.balanceOf(address(strategy)), toAirdrop); + checkStrategyTotals(strategy, _amount, _amount - toAirdrop, toAirdrop); + + vm.prank(keeper); + strategy.tend(); + + // Should have deposited the toAirdrop amount but no other changes + checkStrategyTotals(strategy, _amount, _amount, 0); + assertEq( + asset.balanceOf(address(yieldSource)), + _amount + toAirdrop, + "!yieldSource" + ); + assertEq(strategy.pricePerShare(), wad, "!pps"); + + // Make sure we now report the profit correctly + vm.prank(keeper); + strategy.report(); + + skip(profitMaxUnlockTime); + + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + + uint256 beforeBalance = asset.balanceOf(user); + vm.prank(user); + strategy.redeem(_amount, user, user); + + // should have pulled out the deposit plus profit that was reported but not the second airdrop + assertEq(asset.balanceOf(user), beforeBalance + _amount + toAirdrop); + assertEq(asset.balanceOf(address(yieldSource)), 0); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_tend_idleFunds_harvestProfit( + uint256 _amount, + uint16 _profitFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _profitFactor = uint16(bound(uint256(_profitFactor), 1, MAX_BPS)); + + // Use the illiquid mock strategy so it doesn't deposit all funds + strategy = IMockStrategy(setUpIlliquidStrategy()); + + setFees(0, 0); + // nothing has happened pps should be 1 + uint256 pricePerShare = strategy.pricePerShare(); + assertEq(pricePerShare, wad); + + // deposit into the vault + mintAndDepositIntoStrategy(strategy, user, _amount); + + uint256 expectedDeposit = _amount / 2; + checkStrategyTotals( + strategy, + _amount, + expectedDeposit, + _amount - expectedDeposit, + _amount + ); + + assertEq( + asset.balanceOf(address(yieldSource)), + expectedDeposit, + "!yieldSource" + ); + // should still be 1 + assertEq(strategy.pricePerShare(), wad); + + // airdrop to strategy to simulate a harvesting of rewards + uint256 toAirdrop = (_amount * _profitFactor) / MAX_BPS; + asset.mint(address(strategy), toAirdrop); + assertEq( + asset.balanceOf(address(strategy)), + _amount - expectedDeposit + toAirdrop + ); + + vm.prank(keeper); + strategy.tend(); + + // Should have withdrawn all the funds from the yield source + checkStrategyTotals(strategy, _amount, 0, _amount, _amount); + assertEq(asset.balanceOf(address(yieldSource)), 0, "!yieldSource"); + assertEq(asset.balanceOf(address(strategy)), _amount + toAirdrop); + assertEq(strategy.pricePerShare(), wad, "!pps"); + + // Make sure we now report the profit correctly + vm.prank(keeper); + strategy.report(); + + checkStrategyTotals( + strategy, + _amount + toAirdrop, + (_amount + toAirdrop) / 2, + (_amount + toAirdrop) - ((_amount + toAirdrop) / 2) + ); + assertEq( + asset.balanceOf(address(yieldSource)), + (_amount + toAirdrop) / 2 + ); + + skip(profitMaxUnlockTime); + + assertRelApproxEq( + strategy.pricePerShare(), + wad + ((wad * _profitFactor) / MAX_BPS), + MAX_BPS + ); + } + + function test_withdrawWithUnrealizedLoss_reverts( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = (_amount * _lossFactor) / MAX_BPS; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + vm.expectRevert("too much loss"); + vm.prank(_address); + strategy.withdraw(_amount, _address, _address); + } + + function test_withdrawWithUnrealizedLoss_withMaxLoss( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = (_amount * _lossFactor) / MAX_BPS; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + uint256 beforeBalance = asset.balanceOf(_address); + uint256 expectedOut = _amount - toLose; + // Withdraw the full amount before the loss is reported. + vm.prank(_address); + strategy.withdraw(_amount, _address, _address, _lossFactor); + + uint256 afterBalance = asset.balanceOf(_address); + + assertEq(afterBalance - beforeBalance, expectedOut); + assertEq(strategy.pricePerShare(), wad); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_redeemWithUnrealizedLoss( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = (_amount * _lossFactor) / MAX_BPS; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + uint256 beforeBalance = asset.balanceOf(_address); + uint256 expectedOut = _amount - toLose; + // Withdraw the full amount before the loss is reported. + vm.prank(_address); + strategy.redeem(_amount, _address, _address); + + uint256 afterBalance = asset.balanceOf(_address); + + assertEq(afterBalance - beforeBalance, expectedOut); + assertEq(strategy.pricePerShare(), wad); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_redeemWithUnrealizedLoss_allowNoLoss_reverts( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = (_amount * _lossFactor) / MAX_BPS; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + vm.expectRevert("too much loss"); + vm.prank(_address); + strategy.redeem(_amount, _address, _address, 0); + } + + function test_redeemWithUnrealizedLoss_customMaxLoss( + address _address, + uint256 _amount, + uint16 _lossFactor + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + _lossFactor = uint16(bound(uint256(_lossFactor), 10, MAX_BPS)); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = (_amount * _lossFactor) / MAX_BPS; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + uint256 beforeBalance = asset.balanceOf(_address); + uint256 expectedOut = _amount - toLose; + + // First set it to just under the expected loss. + vm.expectRevert("too much loss"); + vm.prank(_address); + strategy.redeem(_amount, _address, _address, _lossFactor - 1); + + // Now redeem with the correct loss. + vm.prank(_address); + strategy.redeem(_amount, _address, _address, _lossFactor); + + uint256 afterBalance = asset.balanceOf(_address); + + assertEq(afterBalance - beforeBalance, expectedOut); + assertEq(strategy.pricePerShare(), wad); + checkStrategyTotals(strategy, 0, 0, 0, 0); + } + + function test_maxUintDeposit_depositsBalance( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + asset.mint(_address, _amount); + + vm.prank(_address); + asset.approve(address(strategy), _amount); + + assertEq(asset.balanceOf(_address), _amount); + + vm.prank(_address); + strategy.deposit(type(uint256).max, _address); + + // Should just deposit the available amount. + checkStrategyTotals(strategy, _amount, _amount, 0, _amount); + + assertEq(asset.balanceOf(_address), 0); + assertEq(strategy.balanceOf(_address), _amount); + assertEq(asset.balanceOf(address(strategy)), 0); + + assertEq(asset.balanceOf(address(yieldSource)), _amount); + } + + function test_deposit_zeroAssetsPositiveSupply_reverts( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = _amount; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + vm.prank(keeper); + strategy.report(); + + // Should still have shares but no assets + checkStrategyTotals(strategy, 0, 0, 0, _amount); + + assertEq(strategy.balanceOf(_address), _amount); + assertEq(asset.balanceOf(address(strategy)), 0); + assertEq(asset.balanceOf(address(yieldSource)), 0); + + asset.mint(_address, _amount); + vm.prank(_address); + asset.approve(address(strategy), _amount); + + vm.expectRevert("ZERO_SHARES"); + vm.prank(_address); + strategy.deposit(_amount, _address); + + assertEq(strategy.convertToAssets(_amount), 0); + assertEq(strategy.convertToShares(_amount), 0); + assertEq(strategy.pricePerShare(), 0); + } + + function test_mint_zeroAssetsPositiveSupply_reverts( + address _address, + uint256 _amount + ) public { + _amount = bound(_amount, minFuzzAmount, maxFuzzAmount); + vm.assume( + _address != address(0) && + _address != address(strategy) && + _address != address(yieldSource) + ); + + setFees(0, 0); + mintAndDepositIntoStrategy(strategy, _address, _amount); + + uint256 toLose = _amount; + // Simulate a loss. + vm.prank(address(yieldSource)); + asset.transfer(address(69), toLose); + + vm.prank(keeper); + strategy.report(); + + // Should still have shares but no assets + checkStrategyTotals(strategy, 0, 0, 0, _amount); + + assertEq(strategy.balanceOf(_address), _amount); + assertEq(asset.balanceOf(address(strategy)), 0); + assertEq(asset.balanceOf(address(yieldSource)), 0); + + asset.mint(_address, _amount); + vm.prank(_address); + asset.approve(address(strategy), _amount); + + vm.expectRevert("ZERO_ASSETS"); + vm.prank(_address); + strategy.mint(_amount, _address); + + assertEq(strategy.convertToAssets(_amount), 0); + assertEq(strategy.convertToShares(_amount), 0); + assertEq(strategy.pricePerShare(), 0); + } +} diff --git a/src/test/mocks/LegacyMockStrategy.sol b/src/test/mocks/LegacyMockStrategy.sol new file mode 100644 index 0000000..b25a948 --- /dev/null +++ b/src/test/mocks/LegacyMockStrategy.sol @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-3.0 +pragma solidity >=0.8.18; + +import {MockYieldSource} from "./MockYieldSource.sol"; +import {BaseStrategy, ERC20, TokenizedStrategy} from "../../BaseStrategy.sol"; + +contract LegacyMockStrategy is BaseStrategy { + address public yieldSource; + bool public trigger; + bool public managed; + bool public kept; + bool public emergentizated; + + constructor( + address _asset, + address _yieldSource + ) BaseStrategy(_asset, "Test Strategy") { + initialize(_asset, _yieldSource); + } + + function initialize(address _asset, address _yieldSource) public { + require(yieldSource == address(0)); + yieldSource = _yieldSource; + ERC20(_asset).approve(_yieldSource, type(uint256).max); + } + + function _deployFunds(uint256 _amount) internal override { + MockYieldSource(yieldSource).deposit(_amount); + } + + function _freeFunds(uint256 _amount) internal override { + MockYieldSource(yieldSource).withdraw(_amount); + } + + function _harvestAndReport() internal override returns (uint256) { + MockYieldSource(yieldSource).harvest(); + uint256 balance = ERC20(asset).balanceOf(address(this)); + if (balance > 0 && !TokenizedStrategy.isShutdown()) { + MockYieldSource(yieldSource).deposit(balance); + } + return + MockYieldSource(yieldSource).balance() + + ERC20(asset).balanceOf(address(this)); + } + + function _tend(uint256 /*_idle*/) internal override { + uint256 balance = ERC20(asset).balanceOf(address(this)); + if (balance > 0) { + MockYieldSource(yieldSource).deposit(balance); + } + } + + function _emergencyWithdraw(uint256 _amount) internal override { + MockYieldSource(yieldSource).withdraw(_amount); + } + + function _tendTrigger() internal view override returns (bool) { + return trigger; + } + + function setTrigger(bool _trigger) external { + trigger = _trigger; + } + + function onlyLetManagers() public onlyManagement { + managed = true; + } + + function onlyLetKeepersIn() public onlyKeepers { + kept = true; + } + + function onlyLetEmergencyAdminsIn() public onlyEmergencyAuthorized { + emergentizated = true; + } +} + +contract LegacyMockIlliquidStrategy is BaseStrategy { + address public yieldSource; + bool public whitelist; + mapping(address => bool) public allowed; + + constructor( + address _asset, + address _yieldSource + ) BaseStrategy(_asset, "Test Strategy") { + yieldSource = _yieldSource; + ERC20(_asset).approve(_yieldSource, type(uint256).max); + } + + function _deployFunds(uint256 _amount) internal override { + MockYieldSource(yieldSource).deposit(_amount / 2); + } + + function _freeFunds(uint256 /*_amount*/) internal override { + // Keep funds illiquid for legacy withdrawal-limit tests. + } + + function _harvestAndReport() internal override returns (uint256) { + MockYieldSource(yieldSource).harvest(); + uint256 balance = ERC20(asset).balanceOf(address(this)); + if (balance > 0) { + MockYieldSource(yieldSource).deposit(balance / 2); + } + return + MockYieldSource(yieldSource).balance() + + ERC20(asset).balanceOf(address(this)); + } + + function _tend(uint256 /*_idle*/) internal override { + uint256 balance = MockYieldSource(yieldSource).balance(); + if (balance > 0) { + MockYieldSource(yieldSource).withdraw(balance); + } + } + + function availableDepositLimit( + address _owner + ) public view override returns (uint256) { + if (whitelist && !allowed[_owner]) { + return 0; + } else { + return super.availableDepositLimit(_owner); + } + } + + function availableWithdrawLimit( + address /*_owner*/ + ) public view override returns (uint256) { + return asset.balanceOf(address(this)); + } + + function setWhitelist(bool _bool) external { + whitelist = _bool; + } + + function allow(address _address) external { + allowed[_address] = true; + } +} diff --git a/src/test/mocks/MockStorage.sol b/src/test/mocks/MockStorage.sol index a1e3c46..c2f6631 100644 --- a/src/test/mocks/MockStorage.sol +++ b/src/test/mocks/MockStorage.sol @@ -6,45 +6,41 @@ import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // use `make inspect contract=MockStorage` to easy view the structs storage layout. // prettier-ignore contract MockStorage { - // The ERC20 compliant underlying asset that will be - // used by the Strategy - ERC20 asset; - - - // These are the corresponding ERC20 variables needed for the - // strategies token that is issued and burned on each deposit or withdraw. - uint8 decimals; // The amount of decimals that `asset` and strategy use. - - string name; // The name of the token for the strategy. - uint256 totalSupply; // The total amount of shares currently issued. - mapping(address => uint256) nonces; // Mapping of nonces used for permit functions. - mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares. - mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. - - - // Assets data to track the last realized total the strategy held. - uint256 lastTotalAssets; - uint256 profitUnlockingRate; - uint96 fullProfitUnlockDate; - // Variables for profit reporting. - // We use uint96 for time stamps to fit in the same slot as an address. - // We will surely all be dead by the time the slot overflows. - address keeper; // Address given permission to call {report} and {tend}. - uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over. - uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. - address performanceFeeRecipient; // The address to pay the `performanceFee` to. - uint96 lastReport; // The last time a report updated the lock schedule. - - - // Access management variables. - address management; // Main address that can set all configurable variables. - address pendingManagement; // Address that is pending to take over `management`. - address emergencyAdmin; // Address to act in emergencies as well as `management`. - - - // Strategy status checks. - uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. - bool shutdown; // Bool that can be used to stop deposits into the strategy. - bool paused; // Bool that can be used to stop user facing 4626 functions. - uint72 lastAccrual; // The last time accounting synced. + // The ERC20 compliant underlying asset that will be + // used by the Strategy + ERC20 asset; + + // These are the corresponding ERC20 variables needed for the + // strategies token that is issued and burned on each deposit or withdraw. + uint8 decimals; // The amount of decimals that `asset` and strategy use. + + string name; // The name of the token for the strategy. + uint256 totalSupply; // The total amount of shares currently issued. + mapping(address => uint256) nonces; // Mapping of nonces used for permit functions. + mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares. + mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. + + // Assets data to track the last realized total the strategy held. + uint256 lastTotalAssets; + uint256 profitUnlockingRate; + uint96 fullProfitUnlockDate; + // Variables for profit reporting. + // We use uint96 for time stamps to fit in the same slot as an address. + // We will surely all be dead by the time the slot overflows. + address keeper; // Address given permission to call {report} and {tend}. + uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over. + uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. + address performanceFeeRecipient; // The address to pay the `performanceFee` to. + uint96 lastReport; // The last time a report updated the lock schedule. + + // Access management variables. + address management; // Main address that can set all configurable variables. + address pendingManagement; // Address that is pending to take over `management`. + address emergencyAdmin; // Address to act in emergencies as well as `management`. + + // Strategy status checks. + uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. + bool shutdown; // Bool that can be used to stop deposits into the strategy. + bool paused; // Bool that can be used to stop user facing 4626 functions. + uint72 lastAccrual; // The last time accounting synced. } diff --git a/src/test/utils/Setup.sol b/src/test/utils/Setup.sol index 8aa6e82..6f739af 100644 --- a/src/test/utils/Setup.sol +++ b/src/test/utils/Setup.sol @@ -78,7 +78,7 @@ contract Setup is ExtendedTest, IEvents { vm.label(performanceFeeRecipient, "Performance Fee Recipient"); } - function setUpStrategy() public returns (address) { + function setUpStrategy() public virtual returns (address) { // we save the mock base strategy as a IMockStrategy to give it the needed interface IMockStrategy _strategy = IMockStrategy( address(new MockStrategy(address(asset), address(yieldSource))) @@ -99,7 +99,7 @@ contract Setup is ExtendedTest, IEvents { return address(_strategy); } - function setUpIlliquidStrategy() public returns (address) { + function setUpIlliquidStrategy() public virtual returns (address) { IMockStrategy _strategy = IMockStrategy( address( new MockIlliquidStrategy(address(asset), address(yieldSource)) From 1632cb08a3b74ad82153a2b678cec6a5281efb6d Mon Sep 17 00:00:00 2001 From: Schlag <89420541+Schlagonia@users.noreply.github.com> Date: Fri, 19 Jun 2026 13:09:32 -0600 Subject: [PATCH 26/27] feat: v3.1.0 (#122) * chore: deploy * chore: docs * chore: address --- README.md | 4 +- SPECIFICATION.md | 29 +- flattened/FlatBaseStrategy.sol | 493 ++++++++++++++++++++++++++------- foundry.toml | 2 +- script/Deploy.s.sol | 17 +- src/BaseStrategy.sol | 43 ++- 6 files changed, 447 insertions(+), 141 deletions(-) diff --git a/README.md b/README.md index c7e46f7..c28d78d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ > [!CAUTION] -> **v3.1.0 risk:** share pricing is driven by `strategyTotalAssets()`. The default returns `lastTotalAssets()`, but strategies that override it for live accounting can move PPS, previews, and conversions before `report()`; if that value is wrong or manipulable, vault shares can be mispriced. +> **v3.1.0 risk:** share pricing is driven by `strategyTotalAssets()`. BaseStrategy defaults this to `lastTotalAssets()`, preserving v3.0.4 report-boundary accounting. Strategies that override it for live accounting can move PPS, previews, and conversions before `report()`; if that value is wrong or manipulable, vault shares can be mispriced. # Yearn Tokenized Strategy @@ -9,7 +9,7 @@ The implementation address that calls are delegated to is pre-set to a constant NOTE: The master branch has these pre-set addresses set based on the deterministic address that testing on a local device will render. These contracts should NOT be used in production and any live versions should use an official [release](https://github.com/yearn/tokenized-strategy/releases). -A Strategy contract can become a fully ERC-4626 compliant vault by inheriting the `BaseStrategy` contract, that uses the fallback function to delegateCall the previously deployed version of `TokenizedStrategy`. A strategist then only needs to override three required functions in their specific strategy, with the option to override `_strategyTotalAssets()` for live accounting. +A Strategy contract can become a fully ERC-4626 compliant vault by inheriting the `BaseStrategy` contract, that uses the fallback function to delegateCall the previously deployed version of `TokenizedStrategy`. A strategist then only needs to override three required functions in their specific strategy. By default `_strategyTotalAssets()` returns `TokenizedStrategy.lastTotalAssets()` so accounting behaves like v3.0.4, with yield and external position changes realized at `report()`. Override `_strategyTotalAssets()` only when the strategy needs read-only live accounting. [TokenizedStrategy](https://github.com/yearn/tokenized-strategy/blob/master/src/TokenizedStrategy.sol) - The implementation contract that holds all logic for every strategy. diff --git a/SPECIFICATION.md b/SPECIFICATION.md index 229f6db..9bede9f 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -48,7 +48,7 @@ The base strategy is a simple abstract contract designed to be inherited by the `tokenizedStrategyAddress`: This is the address the fallback function will use to delegatecall to and is set before deployment to a constant so it can never be changed. -`TokenizedStrategy`: This is an immutable set on deployment by casting address(this) through an ITokenizedStrategy interface. The variable should be used in a similar manner as a linked library would be to have a simple method to read from the Strategies storage internally. Setting it to address(this) means anything using this variable will static call itself which should hit the fallback and then delegatecall the TokenizedStrategy retrieving the correct variables. +`TokenizedStrategy`: This is the local `TokenizedStrategyLib` alias used by BaseStrategy to read TokenizedStrategy storage and call TokenizedStrategy views through `address(this)`. It behaves like a linked-library helper for the strategy's own storage; it is not an implementation address variable. Unknown external calls still hit the fallback and delegatecall the `tokenizedStrategyAddress` implementation. `asset`: The immutable ERC20 instance of the underlying asset being used. @@ -60,9 +60,9 @@ The majority of functions in the BaseStrategy are either external functions with `freeFunds(uint256)/_freeFunds(uint256)`: Called by the TokenizedStrategy during withdraws to get the amount of the uint256 parameter freed up in order to process the withdraw. -`harvestAndReport()/_harvestAndReport()`: Called during reports to tell the strategy a trusted address has called it and to harvest any rewards re-deploy any loose funds and return the actual amount of funds the strategy holds. +`harvestAndReport()/_harvestAndReport()`: Called during reports to tell the strategy a trusted address has called it and to harvest any rewards, re-deploy any loose funds and return the actual amount of funds the strategy holds. With the default BaseStrategy accounting this is the point where yield and external position changes are realized, preserving v3.0.4 behavior. -`tendThis(uint256)/_tend(uint256)`: Called by the TokenizedStrategy during tend calls to tell the strategy a trusted address has called tend and it has the uint256 parameter of loose asset available to deposit. NOTE: we use `tendThis` to avoid function signature collisions so that `tend` will be forwarded to the TokenizedStrategy. If `_strategyTotalAssets()` is overridden for constant accrual, a tend is not an accounting boundary: value changes it makes price into views through simulated totals and are realized by the next state-changing accrual, not only by a report. +`tendThis(uint256)/_tend(uint256)`: Called by the TokenizedStrategy during tend calls to tell the strategy a trusted address has called tend and it has the uint256 parameter of loose asset available to deposit. NOTE: we use `tendThis` to avoid function signature collisions so that `tend` will be forwarded to the TokenizedStrategy. Under the default `_strategyTotalAssets()` implementation, value changes made by a tend remain report-boundary accounting. If `_strategyTotalAssets()` is overridden for constant accrual, a tend is not an accounting boundary: value changes it makes price into views through simulated totals and are realized by the next state-changing accrual, not only by a report. `tendTrigger()/_tendTrigger()`: View function to return if a tend call is needed. @@ -106,17 +106,16 @@ The strategy issues shares to each depositor to track their relative share of as They are ERC4626 compliant. Please read [ERC4626 compliance](https://hackmd.io/cOFvpyR-SxWArfthhLJb5g#ERC4626-compliance) to understand the implications. #### Accounting -The strategy will evaluate profit and losses from the yield generating activities. +The strategy stores `lastTotalAssets` as the realized accounting baseline. -This is done comparing the current totalAssets of the strategy with the amount returned from _harvestAndReport() +With the default BaseStrategy implementation, `_strategyTotalAssets()` returns `TokenizedStrategy.lastTotalAssets()`. This preserves v3.0.4 report-boundary accounting: normal ERC4626 writes use the stored baseline, and yield, donations or external position changes do not enter PPS until a keeper calls `report()` and `_harvestAndReport()` returns the updated total. -If totalAssets < newTotalAssets: the vault will record a profit -If totalAssets > newTotalAssets: the vault will record a loss +A strategy can opt into live accounting by overriding `_strategyTotalAssets()` with a strictly read-only estimate of all assets. In that mode, views simulate any delta from `lastTotalAssets` when the current block is not latched, and state-changing flows accrue that delta before continuing. Live profit charges fees immediately and updates `lastTotalAssets`; live loss can burn locked profit shares before updating the baseline. -Both loss and profit will impact strategy's totalAssets, increasing if there are profits, decreasing if there are losses. +`report()` always syncs the live estimate first, then calls `_harvestAndReport()` for harvestable or report-only accounting. Profit or loss from the report is the difference between `lastTotalAssets` after the pre-report sync and the amount returned by `_harvestAndReport()`. #### Fees -Fee assessment and distribution is handled during each `report` call after profits or losses are recorded. +Fee assessment and distribution is handled during each `report` call after profits or losses are recorded. If a strategy opts into live accounting, fee assessment is also handled during state-changing accruals that realize live profit. With the default BaseStrategy implementation, `_strategyTotalAssets()` returns `lastTotalAssets()`, so live accrual does not introduce profit and fees remain report-boundary by default. It will report the amount of fees that need to be charged and the strategy will issue shares for that amount of fees. @@ -125,7 +124,7 @@ There are two potential fees. Performance fees and protocol fees. Performance fe Protocol fees are configured by Yearn governance through the Factory and are taken as a percent of the performanceFees charged. I.E. profit = 100, performance fees = 20% protocol fees = 10%. Then total fees charged = 100 * .2 = 20 of which 10% is sent to the protocol fee recipient (2) and 90% (18) is sent the strategy specific `performanceFeeRecipient`. ### Profit distribution -Profit from report calls will accumulate in a buffer. This buffer will be linearly unlocked over the locking period seconds at profitUnlockingRate. +Profit from report calls will accumulate in a buffer. This buffer will be linearly unlocked over the locking period seconds at profitUnlockingRate. Live-accrued profit from an overridden `_strategyTotalAssets()` is not report-locked; it updates the realized baseline immediately after fees. Profits will be locked for a max period of time of profitMaxUnlockTime seconds and will be gradually distributed. To avoid spending too much gas for profit unlock, the amount of time a profit will be locked is a weighted average between the new profit and the previous profit. @@ -182,7 +181,7 @@ Once this is called it will stop any further deposit or mints but will have no e This can be used in an emergency or simply to retire a vault. -Once a strategy is shutdown or paused, management or emergencyAdmin can also call `emergencyWithdraw(amount)`. Which will tell the strategy to withdraw a specified `amount` from the yield source and keep it as idle in the vault. This function performs no accounting update at call time, so the rescue path has no dependency on the strategy's asset estimate. Any profit or loss caused by the unwind prices into views through simulated totals and is realized by the next state-changing accrual or report. +Once a strategy is shutdown or paused, management or emergencyAdmin can also call `emergencyWithdraw(amount)`. Which will tell the strategy to withdraw a specified `amount` from the yield source and keep it as idle in the vault. This function performs no accounting update at call time, so the rescue path has no dependency on the strategy's asset estimate. With the default `_strategyTotalAssets()` implementation, any profit or loss caused by the unwind remains report-boundary accounting. If `_strategyTotalAssets()` is overridden for live accounting, the unwind can price into views through simulated totals and be realized by the next state-changing accrual or report. All other emergency functionality is left up to the individual strategist. @@ -191,7 +190,7 @@ Withdrawals and redemptions are paused by `setPaused(true)`, which can be called ## Use -A strategist can simply inherit the BaseStrategy.sol contract and override 3 required functions with their specific needs. They can also override `_strategyTotalAssets()` if they want live accounting instead of the default report-boundary accounting. +A strategist can simply inherit the BaseStrategy.sol contract and override 3 required functions with their specific needs. The default `_strategyTotalAssets()` returns `TokenizedStrategy.lastTotalAssets()`, preserving v3.0.4 report-boundary accounting. They can override `_strategyTotalAssets()` if they want live accounting from a read-only current asset estimate. The strategies code has been designed as a non-opinionated system to distribute funds of depositors to a single yield generating opportunity while managing accounting in a robust way. @@ -231,15 +230,15 @@ Strategists should be able to use a pre-built "Strategy Mix" that will contain t While it can be possible to deploy a completely ERC-4626 compliant vault with just those three functions it does allow for further customization if the strategist desires. -*_strategyTotalAssets()*: By default this returns `TokenizedStrategy.lastTotalAssets()`, preserving report-boundary accounting. Override it only when the strategy needs live accounting from a read-only current asset estimate. +*_strategyTotalAssets()*: By default this returns `TokenizedStrategy.lastTotalAssets()`, preserving v3.0.4 report-boundary accounting. Override it only when the strategy needs live accounting from a read-only current asset estimate. -*_tend* and *_tendTrigger* can be overridden to signal to keepers the need for any sort of maintenance or reward selling between reports. If `_strategyTotalAssets()` is overridden for constant accrual, any value change made during a tend affects view pricing through simulated totals and is realized by the next state-changing accrual rather than waiting for a report. +*_tend* and *_tendTrigger* can be overridden to signal to keepers the need for any sort of maintenance or reward selling between reports. With the default `_strategyTotalAssets()` implementation, value changes made during a tend remain report-boundary accounting. If `_strategyTotalAssets()` is overridden for constant accrual, those value changes affect view pricing through simulated totals and are realized by the next state-changing accrual rather than waiting for a report. *availableDepositLimit(address _owner)* can be overridden to implement any type of deposit limit. *availableWithdrawLimit(address _owner)* can be used to limit the amount that a user can withdraw at any given moment. -*_emergencyWithdraw(uint256 _amount)* can be overridden to provide a manual method for management to pull funds from a yield source in an emergency when the vault is shutdown. +*_emergencyWithdraw(uint256 _amount)* can be overridden to provide a manual method for management to pull funds from a yield source in an emergency when the vault is shutdown. It does not perform accounting itself; default strategies realize any unwind profit or loss at report, while live-accounting strategies can realize it through the next state-changing accrual. ## Deployment All strategies deployed will have the address of the deployed 'TokenizedStrategy' set as a constant to be used as the address to forward all external calls to that are not defined in the Strategy. diff --git a/flattened/FlatBaseStrategy.sol b/flattened/FlatBaseStrategy.sol index 8a80d76..82698c3 100644 --- a/flattened/FlatBaseStrategy.sol +++ b/flattened/FlatBaseStrategy.sol @@ -1,6 +1,34 @@ // SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.8.18 ^0.8.0; +// lib/openzeppelin-contracts/contracts/utils/Context.sol + +// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.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 Context { + function _msgSender() internal view virtual returns (address) { + return msg.sender; + } + + function _msgData() internal view virtual returns (bytes calldata) { + return msg.data; + } + + function _contextSuffixLength() internal view virtual returns (uint256) { + return 0; + } +} + // lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) @@ -169,34 +197,6 @@ interface IERC20Permit { function DOMAIN_SEPARATOR() external view returns (bytes32); } -// lib/openzeppelin-contracts/contracts/utils/Context.sol - -// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.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 Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } - - function _contextSuffixLength() internal view virtual returns (uint256) { - return 0; - } -} - // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) @@ -823,6 +823,8 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { event StrategyShutdown(); + event UpdatePaused(bool paused); + event NewTokenizedStrategy( address indexed strategy, address indexed asset, @@ -836,6 +838,13 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { uint256 performanceFees ); + event Accrued( + uint256 profit, + uint256 loss, + uint256 protocolFees, + uint256 performanceFees + ); + event UpdatePerformanceFeeRecipient( address indexed newPerformanceFeeRecipient ); @@ -946,8 +955,14 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { function lastReport() external view returns (uint256); + function lastAccrual() external view returns (uint256); + + function lastTotalAssets() external view returns (uint256); + function isShutdown() external view returns (bool); + function isPaused() external view returns (bool); + function unlockedShares() external view returns (uint256); /*////////////////////////////////////////////////////////////// @@ -974,12 +989,268 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { function shutdownStrategy() external; + function setPaused(bool paused) external; + function emergencyWithdraw(uint256 _amount) external; } -// src/BaseStrategy.sol +// src/libraries/TokenizedStrategyLib.sol + +library TokenizedStrategyLib { + bytes32 internal constant BASE_STRATEGY_STORAGE = + bytes32(uint256(keccak256("yearn.base.strategy.storage")) - 1); + + uint8 internal constant ENTERED = 2; + uint8 internal constant NOT_ENTERED = 1; + + // prettier-ignore + struct StrategyData { + ERC20 asset; + uint8 decimals; + string name; + uint256 totalSupply; + mapping(address => uint256) nonces; + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowances; + uint256 lastTotalAssets; + uint256 profitUnlockingRate; + uint96 fullProfitUnlockDate; + address keeper; + uint32 profitMaxUnlockTime; + uint16 performanceFee; + address performanceFeeRecipient; + uint96 lastReport; + address management; + address pendingManagement; + address emergencyAdmin; + uint8 entered; + bool shutdown; + bool paused; + uint72 lastAccrual; + } + + function strategyStorage() internal pure returns (StrategyData storage S) { + bytes32 slot = BASE_STRATEGY_STORAGE; + assembly { + S.slot := slot + } + } + + function asset() internal view returns (address) { + return address(strategyStorage().asset); + } + + function name() internal view returns (string memory) { + return strategyStorage().name; + } + + function symbol() internal view returns (string memory) { + return ITokenizedStrategy(address(this)).symbol(); + } + + function decimals() internal view returns (uint8) { + return strategyStorage().decimals; + } + + function apiVersion() internal view returns (string memory) { + return ITokenizedStrategy(address(this)).apiVersion(); + } + + function MAX_FEE() internal view returns (uint16) { + return ITokenizedStrategy(address(this)).MAX_FEE(); + } + + function FACTORY() internal view returns (address) { + return ITokenizedStrategy(address(this)).FACTORY(); + } + + function management() internal view returns (address) { + return strategyStorage().management; + } + + function pendingManagement() internal view returns (address) { + return strategyStorage().pendingManagement; + } + + function keeper() internal view returns (address) { + return strategyStorage().keeper; + } + + function emergencyAdmin() internal view returns (address) { + return strategyStorage().emergencyAdmin; + } + + function performanceFee() internal view returns (uint16) { + return strategyStorage().performanceFee; + } + + function performanceFeeRecipient() internal view returns (address) { + return strategyStorage().performanceFeeRecipient; + } + + function profitMaxUnlockTime() internal view returns (uint256) { + uint256 _profitMaxUnlockTime = strategyStorage().profitMaxUnlockTime; + if (_profitMaxUnlockTime == type(uint32).max) { + return type(uint256).max; + } + + return _profitMaxUnlockTime; + } + + function lastReport() internal view returns (uint256) { + return uint256(strategyStorage().lastReport); + } + + function lastAccrual() internal view returns (uint256) { + return uint256(strategyStorage().lastAccrual); + } + + function lastTotalAssets() internal view returns (uint256) { + return strategyStorage().lastTotalAssets; + } + + function fullProfitUnlockDate() internal view returns (uint256) { + return uint256(strategyStorage().fullProfitUnlockDate); + } + + function profitUnlockingRate() internal view returns (uint256) { + return strategyStorage().profitUnlockingRate; + } + + function isShutdown() internal view returns (bool) { + return strategyStorage().shutdown; + } + + function isPaused() internal view returns (bool) { + return strategyStorage().paused; + } + + function isEntered() internal view returns (bool) { + return strategyStorage().entered == ENTERED; + } + + function nonReentrantBefore() internal { + StrategyData storage S = strategyStorage(); + // On the first call to nonReentrant, `entered` will be false (2) + require(S.entered != ENTERED, "ReentrancyGuard: reentrant call"); + + // Any calls to nonReentrant after this point will fail + S.entered = ENTERED; + } + + function nonReentrantAfter() internal { + // Reset to false (1) once call has finished. + strategyStorage().entered = NOT_ENTERED; + } + + function totalAssets() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).totalAssets(); + } + + function totalSupply() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).totalSupply(); + } + + function balanceOf(address _account) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).balanceOf(_account); + } + + function allowance( + address _owner, + address _spender + ) internal view returns (uint256) { + return strategyStorage().allowances[_owner][_spender]; + } + + function nonces(address _owner) internal view returns (uint256) { + return strategyStorage().nonces[_owner]; + } + + function DOMAIN_SEPARATOR() internal view returns (bytes32) { + return ITokenizedStrategy(address(this)).DOMAIN_SEPARATOR(); + } + + function unlockedShares() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).unlockedShares(); + } + + function requireManagement(address _sender) internal view { + require(_sender == strategyStorage().management, "!management"); + } + + function requireKeeperOrManagement(address _sender) internal view { + StrategyData storage S = strategyStorage(); + require(_sender == S.keeper || _sender == S.management, "!keeper"); + } + + function requireEmergencyAuthorized(address _sender) internal view { + StrategyData storage S = strategyStorage(); + require( + _sender == S.emergencyAdmin || _sender == S.management, + "!emergency authorized" + ); + } + + function pricePerShare() internal view returns (uint256) { + return ITokenizedStrategy(address(this)).pricePerShare(); + } + + function convertToShares(uint256 _assets) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).convertToShares(_assets); + } + + function convertToAssets(uint256 _shares) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).convertToAssets(_shares); + } + + function previewDeposit(uint256 _assets) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewDeposit(_assets); + } + + function previewMint(uint256 _shares) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewMint(_shares); + } + + function previewWithdraw(uint256 _assets) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewWithdraw(_assets); + } + + function previewRedeem(uint256 _shares) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).previewRedeem(_shares); + } + + function maxDeposit(address _receiver) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxDeposit(_receiver); + } + + function maxMint(address _receiver) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxMint(_receiver); + } + + function maxWithdraw(address _owner) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxWithdraw(_owner); + } + + function maxWithdraw( + address _owner, + uint256 _maxLoss + ) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxWithdraw(_owner, _maxLoss); + } + + function maxRedeem(address _owner) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxRedeem(_owner); + } -// TokenizedStrategy interface used for internal view delegateCalls. + function maxRedeem( + address _owner, + uint256 _maxLoss + ) internal view returns (uint256) { + return ITokenizedStrategy(address(this)).maxRedeem(_owner, _maxLoss); + } +} + +// src/BaseStrategy.sol /** * @title YearnV3 Base Strategy @@ -988,8 +1259,8 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { * BaseStrategy implements all of the required functionality to * seamlessly integrate with the `TokenizedStrategy` implementation contract * allowing anyone to easily build a fully permissionless ERC-4626 compliant - * Vault by inheriting this contract and overriding three simple functions. - + * Vault by inheriting this contract and overriding three required functions. + * * It utilizes an immutable proxy pattern that allows the BaseStrategy * to remain simple and small. All standard logic is held within the * `TokenizedStrategy` and is reused over any n strategies all using the @@ -998,17 +1269,18 @@ interface ITokenizedStrategy is IERC4626, IERC20Permit { * * This contract should be inherited and the three main abstract methods * `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt - * the Strategy to the particular needs it has to generate yield. There are - * other optional methods that can be implemented to further customize - * the strategy if desired. + * the Strategy to the particular needs it has to generate yield. Optional + * methods can be implemented to further customize the strategy if desired. + * `_strategyTotalAssets` defaults to `lastTotalAssets()` to preserve v3.0.4 + * report-boundary accounting and should only be overridden for read-only + * live accounting. * * All default storage for the strategy is controlled and updated by the * `TokenizedStrategy`. The implementation holds a storage struct that * contains all needed global variables in a manual storage slot. This * means strategists can feel free to implement their own custom storage * variables as they need with no concern of collisions. All global variables - * can be viewed within the Strategy by a simple call using the - * `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();. + * can be viewed within the Strategy using `TokenizedStrategy`. */ abstract contract BaseStrategy { /*////////////////////////////////////////////////////////////// @@ -1027,7 +1299,7 @@ abstract contract BaseStrategy { * @dev Use to assure that the call is coming from the strategies management. */ modifier onlyManagement() { - TokenizedStrategy.requireManagement(msg.sender); + TokenizedStrategyLib.requireManagement(msg.sender); _; } @@ -1036,7 +1308,7 @@ abstract contract BaseStrategy { * management or the keeper. */ modifier onlyKeepers() { - TokenizedStrategy.requireKeeperOrManagement(msg.sender); + TokenizedStrategyLib.requireKeeperOrManagement(msg.sender); _; } @@ -1045,8 +1317,18 @@ abstract contract BaseStrategy { * management or the emergency admin. */ modifier onlyEmergencyAuthorized() { - TokenizedStrategy.requireEmergencyAuthorized(msg.sender); + TokenizedStrategyLib.requireEmergencyAuthorized(msg.sender); + _; + } + + /** + * @dev Reuses the TokenizedStrategy reentrancy guard for custom strategy functions. + */ + + modifier nonReentrantTokenized() { + TokenizedStrategyLib.nonReentrantBefore(); _; + TokenizedStrategyLib.nonReentrantAfter(); } /** @@ -1072,9 +1354,8 @@ abstract contract BaseStrategy { * This address should be the same for every strategy, never be adjusted * and always be checked before any integration with the Strategy. */ - // NOTE: This is a holder address based on expected deterministic location for testing address public constant tokenizedStrategyAddress = - 0x2e234DAe75C793f67A35089C9d99245E1C58470b; + 0x310f5Db015E9d6E542fd41bd4542640790791e76; /*////////////////////////////////////////////////////////////// IMMUTABLES @@ -1086,42 +1367,33 @@ abstract contract BaseStrategy { */ ERC20 internal immutable asset; - /** - * @dev This variable is set to address(this) during initialization of each strategy. - * - * This can be used to retrieve storage data within the strategy - * contract as if it were a linked library. - * - * i.e. uint256 totalAssets = TokenizedStrategy.totalAssets() - * - * Using address(this) will mean any calls using this variable will lead - * to a call to itself. Which will hit the fallback function and - * delegateCall that to the actual TokenizedStrategy. - */ - ITokenizedStrategy internal immutable TokenizedStrategy; - /** * @notice Used to initialize the strategy on deployment. * - * This will set the `TokenizedStrategy` variable for easy - * internal view calls to the implementation. As well as - * initializing the default storage variables based on the - * parameters and using the deployer for the permissioned roles. + * This will initialize the default storage variables based on the + * parameters and use the deployer for the permissioned roles. * * @param _asset Address of the underlying asset. * @param _name Name the strategy will use. */ constructor(address _asset, string memory _name) { asset = ERC20(_asset); + _initialize(_asset, _name, msg.sender, msg.sender, msg.sender); + } - // Set instance of the implementation for internal use. - TokenizedStrategy = ITokenizedStrategy(address(this)); - + /// @dev Internal function to initialize the strategy. + function _initialize( + address _asset, + string memory _name, + address _management, + address _performanceFeeRecipient, + address _keeper + ) internal virtual { // Initialize the strategy's storage variables. _delegateCall( abi.encodeCall( ITokenizedStrategy.initialize, - (_asset, _name, msg.sender, msg.sender, msg.sender) + (_asset, _name, _management, _performanceFeeRecipient, _keeper) ) ); @@ -1178,36 +1450,45 @@ abstract contract BaseStrategy { function _freeFunds(uint256 _amount) internal virtual; /** - * @dev Internal function to harvest all rewards, redeploy any idle - * funds and return an accurate accounting of all funds currently - * held by the Strategy. - * - * This should do any needed harvesting, rewards selling, accrual, - * redepositing etc. to get the most accurate view of current assets. - * - * NOTE: All applicable assets including loose assets should be - * accounted for in this function. - * - * Care should be taken when relying on oracles or swap values rather - * than actual amounts as all Strategy profit/loss accounting will - * be done based on this returned value. + * @dev Internal hook used by explicit {report()} accounting syncs. * - * This can still be called post a shutdown, a strategist can check - * `TokenizedStrategy.isShutdown()` to decide if funds should be - * redeployed or simply realize any profits/losses. + * This can harvest rewards, claim fees, realize external position changes + * or perform any other mutable work needed before returning the strategy's + * up-to-date total assets. * - * @return _totalAssets A trusted and accurate account for the total + * @return _reportedAssets A trusted and accurate account for the total * amount of 'asset' the strategy currently holds including idle funds. */ function _harvestAndReport() internal virtual - returns (uint256 _totalAssets); + returns (uint256 _reportedAssets); /*////////////////////////////////////////////////////////////// OPTIONAL TO OVERRIDE BY STRATEGIST //////////////////////////////////////////////////////////////*/ + /** + * @dev Internal function to return the Strategy's current asset estimate. + * + * The default returns `TokenizedStrategy.lastTotalAssets()`, preserving + * v3.0.4 report-boundary accounting. Strategies that want live accounting + * should override this with a strictly read-only estimate of all assets, + * including loose funds. + * + * NOTE: An override must not harvest, claim or otherwise mutate state. + * + * @return _totalAssets The strategy's current asset estimate. + */ + function _strategyTotalAssets() + internal + view + virtual + returns (uint256 _totalAssets) + { + return TokenizedStrategyLib.lastTotalAssets(); + } + /** * @dev Optional function for strategist to override that can * be called in between reports. @@ -1225,7 +1506,14 @@ abstract contract BaseStrategy { * sandwiched can use the tend when a certain threshold * of idle to totalAssets has been reached. * - * This will have no effect on PPS of the strategy till report() is called. + * NOTE: With the default `_strategyTotalAssets`, value changes made here + * remain report-boundary accounting. If `_strategyTotalAssets` is overridden + * for live accounting, this is not an accounting boundary. Value changes + * made here price into {totalAssets}, conversions and previews through + * simulated totals and are realized by the next state-changing accrual (any + * deposit, mint, withdraw, redeem, fee configuration change, or report), not + * only by report(). Slippage or costs incurred here net against any + * unrealized profit before performance fees are charged. * * @param _totalIdle The current amount of idle funds that are available to deploy. */ @@ -1266,7 +1554,7 @@ abstract contract BaseStrategy { * traditional deposit limit or for implementing a whitelist etc. * * EX: - * if(isAllowed[_owner]) return super.availableDepositLimit(_owner); + * if(isAllowed[receiver]) return super.availableDepositLimit(receiver); * * This does not need to take into account any conversion rates * from shares to assets. But should know that any non max uint256 @@ -1274,11 +1562,11 @@ abstract contract BaseStrategy { * custom amounts low enough as not to cause overflow when multiplied * by `totalSupply`. * - * @param . The address that is depositing into the strategy. - * @return . The available amount the `_owner` can deposit in terms of `asset` + * @param . The address that is receiving the shares from the deposit. + * @return . The available amount that can be deposited in terms of `asset` */ function availableDepositLimit( - address /*_owner*/ + address /*receiver*/ ) public view virtual returns (uint256) { return type(uint256).max; } @@ -1289,11 +1577,11 @@ abstract contract BaseStrategy { * be overridden by strategists. * * This function will be called before any withdraw or redeem to enforce - * any limits desired by the strategist. This can be used for illiquid - * or sandwichable strategies. It should never be lower than `totalIdle`. + * any limits desired by the strategist or integrated protocol. This can + * be used for illiquid or sandwichable strategies. * * EX: - * return TokenIzedStrategy.totalIdle(); + * return asset.balanceOf(address(this)); * * This does not need to take into account the `_owner`'s share balance * or conversion rates from shares to assets. @@ -1315,11 +1603,15 @@ abstract contract BaseStrategy { * This should attempt to free `_amount`, noting that `_amount` may * be more than is currently deployed. * - * NOTE: This will not realize any profits or losses. A separate - * {report} will be needed in order to record any profit/loss. If - * a report may need to be called after a shutdown it is important - * to check if the strategy is shutdown during {_harvestAndReport} - * so that it does not simply re-deploy all funds that had been freed. + * NOTE: With the default `_strategyTotalAssets`, any profit or loss caused + * by the unwind remains report-boundary accounting. If `_strategyTotalAssets` + * is overridden for live accounting, unwind profit or loss will be reflected + * in pricing through simulated totals and realized by the next + * state-changing accrual without further action; a {report} is not required + * but can be used for controlled realization. If a report may need to be + * called after a shutdown it is important to check if the strategy is + * shutdown during {_harvestAndReport} so that it does not simply re-deploy + * all funds that had been freed. * * EX: * if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) { @@ -1352,6 +1644,15 @@ abstract contract BaseStrategy { _deployFunds(_amount); } + /** + * @notice Returns the strategy's asset estimate used by TokenizedStrategy. + * @dev Read-only callback for the TokenizedStrategy. BaseStrategy's default + * returns `lastTotalAssets()`, preserving v3.0.4 report-boundary behavior. + */ + function strategyTotalAssets() external view virtual returns (uint256) { + return _strategyTotalAssets(); + } + /** * @notice Should attempt to free the '_amount' of 'asset'. * @dev Callback for the TokenizedStrategy to call during a withdraw @@ -1391,7 +1692,7 @@ abstract contract BaseStrategy { * * We name the function `tendThis` so that `tend` calls are forwarded to * the TokenizedStrategy. - + * * @param _totalIdle The amount of current idle funds that can be * deployed during the tend */ diff --git a/foundry.toml b/foundry.toml index 3e9f50e..9a7c7b9 100644 --- a/foundry.toml +++ b/foundry.toml @@ -4,7 +4,7 @@ out = 'out' libs = ['lib'] solc = "0.8.18" evm_version = "paris" -optimize = true +optimizer = true optimizer_runs = 200 no_match_test = "testFail" diff --git a/script/Deploy.s.sol b/script/Deploy.s.sol index 7a3610b..761f8a7 100644 --- a/script/Deploy.s.sol +++ b/script/Deploy.s.sol @@ -9,8 +9,8 @@ contract Deploy is Script { Deployer public deployer = Deployer(0xba5Ed099633D3B313e4D5F7bdc1305d3c28ba5Ed); - // Vault factory address for v3.0.4 - address public factory = 0x770D0d1Fb036483Ed4AbB6d53c1C88fb277D812F; + // Vault factory address for v3.1.0 + address public factory = 0x310aC28ACF5E514abDbFF9Ab25e21f1bfe22bcAC; function run() external { vm.startBroadcast(); @@ -21,7 +21,14 @@ contract Deploy is Script { abi.encode(factory) ); - bytes32 salt = bytes32(0); + // CreateX guards this raw salt to + // 0xf45fdd830e8ee48b85bd4c66eb52737e9c490d2bf9485311e0c013ce2b936820, + // yielding 0x310f5Db015E9d6E542fd41bd4542640790791e76. + bytes32 salt = bytes32( + uint256( + 0x000000000000000000000000000000000000000000000000000000000019fdf1 + ) + ); address contractAddress = deployer.deployCreate2(salt, bytecode); @@ -31,11 +38,11 @@ contract Deploy is Script { } } -contract Deployer { +interface Deployer { event ContractCreation(address indexed newContract, bytes32 indexed salt); function deployCreate2( bytes32 salt, bytes memory initCode - ) public payable returns (address newContract) {} + ) external payable returns (address newContract); } diff --git a/src/BaseStrategy.sol b/src/BaseStrategy.sol index e201082..3b45be2 100644 --- a/src/BaseStrategy.sol +++ b/src/BaseStrategy.sol @@ -24,8 +24,10 @@ import {TokenizedStrategyLib as TokenizedStrategy} from "./libraries/TokenizedSt * This contract should be inherited and the three main abstract methods * `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt * the Strategy to the particular needs it has to generate yield. Optional - * methods, including `_strategyTotalAssets`, can be implemented to further - * customize the strategy if desired. + * methods can be implemented to further customize the strategy if desired. + * `_strategyTotalAssets` defaults to `lastTotalAssets()` to preserve v3.0.4 + * report-boundary accounting and should only be overridden for read-only + * live accounting. * * All default storage for the strategy is controlled and updated by the * `TokenizedStrategy`. The implementation holds a storage struct that @@ -224,10 +226,10 @@ abstract contract BaseStrategy { /** * @dev Internal function to return the Strategy's current asset estimate. * - * The default returns the last realized total assets, preserving the - * report-boundary accounting behavior used before live accrual. Strategies - * that want constant accrual should override this with a strictly read-only - * estimate of all assets, including loose funds. + * The default returns `TokenizedStrategy.lastTotalAssets()`, preserving + * v3.0.4 report-boundary accounting. Strategies that want live accounting + * should override this with a strictly read-only estimate of all assets, + * including loose funds. * * NOTE: An override must not harvest, claim or otherwise mutate state. * @@ -259,13 +261,11 @@ abstract contract BaseStrategy { * sandwiched can use the tend when a certain threshold * of idle to totalAssets has been reached. * - * NOTE: If `_strategyTotalAssets` is overridden for constant accrual, this - * is not an accounting boundary. Value changes made here price into - * {totalAssets}, conversions and previews through simulated totals and are - * realized by the next state-changing accrual (any deposit, mint, withdraw, - * redeem, fee configuration change, or report) — not only by report(). - * Slippage or costs incurred here net against any unrealized profit before - * performance fees are charged. + * NOTE: With the default `_strategyTotalAssets`, value changes made here + * remain report-boundary accounting. If `_strategyTotalAssets` is overridden + * for live accounting value changes made here price into {totalAssets}, + * conversions and previews through simulated totals and are realized by + * the next state-changing accrual * * @param _totalIdle The current amount of idle funds that are available to deploy. */ @@ -355,13 +355,11 @@ abstract contract BaseStrategy { * This should attempt to free `_amount`, noting that `_amount` may * be more than is currently deployed. * - * NOTE: If `_strategyTotalAssets` is overridden for constant accrual, any - * profit or loss caused by the unwind will be reflected in pricing through - * simulated totals and realized by the next state-changing accrual without - * further action; a {report} is not required but can be used for controlled - * realization. If a report may need to be called after a shutdown it is - * important to check if the strategy is shutdown during {_harvestAndReport} - * so that it does not simply re-deploy all funds that had been freed. + * NOTE: With the default `_strategyTotalAssets`, any profit or loss caused + * by the unwind remains report-boundary accounting. If `_strategyTotalAssets` + * is overridden for live accounting, unwind profit or loss will be reflected + * in pricing through simulated totals and realized by the next + * state-changing accrual without further action; a {report} is not required. * * EX: * if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) { @@ -395,8 +393,9 @@ abstract contract BaseStrategy { } /** - * @notice Returns the strategies best current estimate for total assets. - * @dev Read-only callback for the TokenizedStrategy. + * @notice Returns the strategy's asset estimate used by TokenizedStrategy. + * @dev Read-only callback for the TokenizedStrategy. BaseStrategy's default + * returns `lastTotalAssets()`, preserving v3.0.4 report-boundary behavior. */ function strategyTotalAssets() external view virtual returns (uint256) { return _strategyTotalAssets(); From cdcec993c885931b8f0a5b115a66185cd280d712 Mon Sep 17 00:00:00 2001 From: Schlagonia Date: Fri, 19 Jun 2026 13:11:24 -0600 Subject: [PATCH 27/27] chore: flatten --- flattened/FlatTokenizedStrategy.sol | 6472 ++++++++++++++------------- 1 file changed, 3402 insertions(+), 3070 deletions(-) diff --git a/flattened/FlatTokenizedStrategy.sol b/flattened/FlatTokenizedStrategy.sol index 9590328..370f685 100644 --- a/flattened/FlatTokenizedStrategy.sol +++ b/flattened/FlatTokenizedStrategy.sol @@ -1,3378 +1,3710 @@ - // SPDX-License-Identifier: AGPL-3.0 - pragma solidity >=0.8.18 ^0.8.0 ^0.8.1; - - // lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol - - // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) - - /** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ - interface IERC20 { - /** - * @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); - - /** - * @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 `to`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount) external returns (bool); - } - - // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol - - // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol) - - /** - * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - * - * ==== Security Considerations - * - * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature - * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be - * considered as an intention to spend the allowance in any specific way. The second is that because permits have - * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should - * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be - * generally recommended is: - * - * ```solidity - * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { - * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} - * doThing(..., value); - * } - * - * function doThing(..., uint256 value) public { - * token.safeTransferFrom(msg.sender, address(this), value); - * ... - * } - * ``` - * - * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of - * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also - * {SafeERC20-safeTransferFrom}). - * - * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so - * contracts should have entry points that don't rely on permit. - */ - interface IERC20Permit { - /** - * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, - * given ``owner``'s signed approval. - * - * IMPORTANT: The same issues {IERC20-approve} has related to transaction - * ordering also apply here. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `deadline` must be a timestamp in the future. - * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` - * over the EIP712-formatted function arguments. - * - the signature must use ``owner``'s current nonce (see {nonces}). - * - * For more information on the signature format, see the - * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP - * section]. - * - * CAUTION: See Security Considerations above. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external; - - /** - * @dev Returns the current nonce for `owner`. This value must be - * included whenever a signature is generated for {permit}. - * - * Every successful call to {permit} increases ``owner``'s nonce by one. This - * prevents a signature from being used multiple times. - */ - function nonces(address owner) external view returns (uint256); - - /** - * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view returns (bytes32); - } - - // lib/openzeppelin-contracts/contracts/utils/Address.sol - - // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) - - /** - * @dev Collection of functions related to the address type - */ - library Address { - /** - * @dev Returns true if `account` is a contract. - * - * [IMPORTANT] - * ==== - * It is unsafe to assume that an address for which this function returns - * false is an externally-owned account (EOA) and not a contract. - * - * Among others, `isContract` will return false for the following - * types of addresses: - * - * - an externally-owned account - * - a contract in construction - * - an address where a contract will be created - * - an address where a contract lived, but was destroyed - * - * Furthermore, `isContract` will also return true if the target contract within - * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, - * which only has an effect at the end of a transaction. - * ==== - * - * [IMPORTANT] - * ==== - * You shouldn't rely on `isContract` to protect against flash loan attacks! - * - * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets - * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract - * constructor. - * ==== - */ - function isContract(address account) internal view returns (bool) { - // This method relies on extcodesize/address.code.length, which returns 0 - // for contracts in construction, since the code is only stored at the end - // of the constructor execution. - - return account.code.length > 0; - } +// SPDX-License-Identifier: AGPL-3.0 +pragma solidity >=0.8.18 ^0.8.0 ^0.8.1; - /** - * @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://consensys.net/diligence/blog/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.8.0/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"); - } +// lib/openzeppelin-contracts/contracts/utils/Address.sol - /** - * @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 functionCallWithValue(target, data, 0, "Address: low-level call failed"); - } +// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) - /** - * @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 Collection of functions related to the address type + */ +library Address { + /** + * @dev Returns true if `account` is a contract. + * + * [IMPORTANT] + * ==== + * It is unsafe to assume that an address for which this function returns + * false is an externally-owned account (EOA) and not a contract. + * + * Among others, `isContract` will return false for the following + * types of addresses: + * + * - an externally-owned account + * - a contract in construction + * - an address where a contract will be created + * - an address where a contract lived, but was destroyed + * + * Furthermore, `isContract` will also return true if the target contract within + * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, + * which only has an effect at the end of a transaction. + * ==== + * + * [IMPORTANT] + * ==== + * You shouldn't rely on `isContract` to protect against flash loan attacks! + * + * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets + * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract + * constructor. + * ==== + */ + function isContract(address account) internal view returns (bool) { + // This method relies on extcodesize/address.code.length, which returns 0 + // for contracts in construction, since the code is only stored at the end + // of the constructor execution. + + return account.code.length > 0; + } - /** - * @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 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://consensys.net/diligence/blog/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.8.0/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 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"); - (bool success, bytes memory returndata) = target.call{value: value}(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } + /** + * @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 functionCallWithValue(target, data, 0, "Address: low-level call failed"); + } - /** - * @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-}[`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-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) { - (bool success, bytes memory returndata) = target.staticcall(data); - return verifyCallResultFromTarget(target, success, returndata, 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-functionCall-address-bytes-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { - return functionDelegateCall(target, data, "Address: low-level delegate call failed"); - } + /** + * @dev Same as {xref-Address-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"); + (bool success, bytes memory returndata) = target.call{value: value}(data); + return verifyCallResultFromTarget(target, success, returndata, errorMessage); + } - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - (bool success, bytes memory returndata) = target.delegatecall(data); - return verifyCallResultFromTarget(target, 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 Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling - * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. - * - * _Available since v4.8._ - */ - function verifyCallResultFromTarget( - address target, - bool success, - bytes memory returndata, - string memory errorMessage - ) internal view returns (bytes memory) { - if (success) { - if (returndata.length == 0) { - // only check isContract if the call was successful and the return data is empty - // otherwise we already know that it was a contract - require(isContract(target), "Address: call to non-contract"); - } - return returndata; - } else { - _revert(returndata, errorMessage); + /** + * @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) { + (bool success, bytes memory returndata) = target.staticcall(data); + return verifyCallResultFromTarget(target, success, returndata, errorMessage); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], + * but performing a delegate call. + * + * _Available since v3.4._ + */ + function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { + return functionDelegateCall(target, data, "Address: low-level delegate call failed"); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], + * but performing a delegate call. + * + * _Available since v3.4._ + */ + function functionDelegateCall( + address target, + bytes memory data, + string memory errorMessage + ) internal returns (bytes memory) { + (bool success, bytes memory returndata) = target.delegatecall(data); + return verifyCallResultFromTarget(target, success, returndata, errorMessage); + } + + /** + * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling + * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. + * + * _Available since v4.8._ + */ + function verifyCallResultFromTarget( + address target, + bool success, + bytes memory returndata, + string memory errorMessage + ) internal view returns (bytes memory) { + if (success) { + if (returndata.length == 0) { + // only check isContract if the call was successful and the return data is empty + // otherwise we already know that it was a contract + require(isContract(target), "Address: call to non-contract"); } + return returndata; + } else { + _revert(returndata, errorMessage); } + } - /** - * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the - * revert reason or 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 { - _revert(returndata, errorMessage); - } + /** + * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the + * revert reason or 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 { + _revert(returndata, errorMessage); } + } - function _revert(bytes memory returndata, string memory errorMessage) private pure { - // 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 - /// @solidity memory-safe-assembly - assembly { - let returndata_size := mload(returndata) - revert(add(32, returndata), returndata_size) - } - } else { - revert(errorMessage); + function _revert(bytes memory returndata, string memory errorMessage) private pure { + // 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 + /// @solidity memory-safe-assembly + assembly { + let returndata_size := mload(returndata) + revert(add(32, returndata), returndata_size) } + } else { + revert(errorMessage); } } +} + +// lib/openzeppelin-contracts/contracts/utils/Context.sol + +// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.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 Context { + function _msgSender() internal view virtual returns (address) { + return msg.sender; + } - // lib/openzeppelin-contracts/contracts/utils/Context.sol + function _msgData() internal view virtual returns (bytes calldata) { + return msg.data; + } - // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol) + function _contextSuffixLength() internal view virtual returns (uint256) { + return 0; + } +} - /** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ - abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } +// src/interfaces/IBaseStrategy.sol - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } +interface IBaseStrategy { + function tokenizedStrategyAddress() external view returns (address); - function _contextSuffixLength() internal view virtual returns (uint256) { - return 0; - } - } + /*////////////////////////////////////////////////////////////// + IMMUTABLE FUNCTIONS + //////////////////////////////////////////////////////////////*/ + + function availableDepositLimit( + address _owner + ) external view returns (uint256); + + function availableWithdrawLimit( + address _owner + ) external view returns (uint256); + + function strategyTotalAssets() external view returns (uint256); - // lib/openzeppelin-contracts/contracts/utils/math/Math.sol + function deployFunds(uint256 _assets) external; - // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) + function freeFunds(uint256 _amount) external; + function harvestAndReport() external returns (uint256); + + function tendThis(uint256 _totalIdle) external; + + function shutdownWithdraw(uint256 _amount) external; + + function tendTrigger() external view returns (bool, bytes memory); +} + +// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol + +// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) + +/** + * @dev Interface of the ERC20 standard as defined in the EIP. + */ +interface IERC20 { /** - * @dev Standard math utilities missing in the Solidity language. - */ - library Math { - enum Rounding { - Down, // Toward negative infinity - Up, // Toward infinity - Zero // Toward zero - } + * @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 Returns the largest of two numbers. - */ - function max(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b ? a : b; - } + /** + * @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); - /** - * @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 amount of tokens in existence. + */ + function totalSupply() external view returns (uint256); - /** - * @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 amount of tokens owned by `account`. + */ + function balanceOf(address account) external view returns (uint256); - /** - * @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 == 0 ? 0 : (a - 1) / b + 1; - } + /** + * @dev Moves `amount` tokens from the caller's account to `to`. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transfer(address to, uint256 amount) external returns (bool); - /** - * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 - * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) - * with further edits by Uniswap Labs also under MIT license. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { - unchecked { - // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use - // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 - // variables such that product = prod1 * 2^256 + prod0. - uint256 prod0; // Least significant 256 bits of the product - uint256 prod1; // Most significant 256 bits of the product - assembly { - let mm := mulmod(x, y, not(0)) - prod0 := mul(x, y) - prod1 := sub(sub(mm, prod0), lt(mm, prod0)) - } + /** + * @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); - // Handle non-overflow cases, 256 by 256 division. - if (prod1 == 0) { - // Solidity will revert if denominator == 0, unlike the div opcode on its own. - // The surrounding unchecked block does not change this fact. - // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. - return prod0 / denominator; - } + /** + * @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); - // Make sure the result is less than 2^256. Also prevents denominator == 0. - require(denominator > prod1, "Math: mulDiv overflow"); + /** + * @dev Moves `amount` tokens from `from` to `to` 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 from, address to, uint256 amount) external returns (bool); +} + +// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol + +// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol) + +/** + * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in + * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. + * + * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by + * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't + * need to send a transaction, and thus is not required to hold Ether at all. + * + * ==== Security Considerations + * + * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature + * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be + * considered as an intention to spend the allowance in any specific way. The second is that because permits have + * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should + * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be + * generally recommended is: + * + * ```solidity + * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { + * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} + * doThing(..., value); + * } + * + * function doThing(..., uint256 value) public { + * token.safeTransferFrom(msg.sender, address(this), value); + * ... + * } + * ``` + * + * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of + * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also + * {SafeERC20-safeTransferFrom}). + * + * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so + * contracts should have entry points that don't rely on permit. + */ +interface IERC20Permit { + /** + * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, + * given ``owner``'s signed approval. + * + * IMPORTANT: The same issues {IERC20-approve} has related to transaction + * ordering also apply here. + * + * Emits an {Approval} event. + * + * Requirements: + * + * - `spender` cannot be the zero address. + * - `deadline` must be a timestamp in the future. + * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` + * over the EIP712-formatted function arguments. + * - the signature must use ``owner``'s current nonce (see {nonces}). + * + * For more information on the signature format, see the + * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP + * section]. + * + * CAUTION: See Security Considerations above. + */ + function permit( + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) external; - /////////////////////////////////////////////// - // 512 by 256 division. - /////////////////////////////////////////////// + /** + * @dev Returns the current nonce for `owner`. This value must be + * included whenever a signature is generated for {permit}. + * + * Every successful call to {permit} increases ``owner``'s nonce by one. This + * prevents a signature from being used multiple times. + */ + function nonces(address owner) external view returns (uint256); - // Make division exact by subtracting the remainder from [prod1 prod0]. - uint256 remainder; - assembly { - // Compute remainder using mulmod. - remainder := mulmod(x, y, denominator) + /** + * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. + */ + // solhint-disable-next-line func-name-mixedcase + function DOMAIN_SEPARATOR() external view returns (bytes32); +} + +// src/interfaces/IFactory.sol + +interface IFactory { + function protocol_fee_config() external view returns (uint16, address); +} + +// lib/openzeppelin-contracts/contracts/utils/math/Math.sol + +// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) + +/** + * @dev Standard math utilities missing in the Solidity language. + */ +library Math { + enum Rounding { + Down, // Toward negative infinity + Up, // Toward infinity + Zero // Toward zero + } - // Subtract 256 bit number from 512 bit number. - prod1 := sub(prod1, gt(remainder, prod0)) - prod0 := sub(prod0, remainder) - } + /** + * @dev Returns the largest of two numbers. + */ + function max(uint256 a, uint256 b) internal pure returns (uint256) { + return a > b ? a : b; + } - // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. - // See https://cs.stackexchange.com/q/138556/92363. + /** + * @dev Returns the smallest of two numbers. + */ + function min(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } - // Does not overflow because the denominator cannot be zero at this stage in the function. - uint256 twos = denominator & (~denominator + 1); - assembly { - // Divide denominator by twos. - denominator := div(denominator, twos) + /** + * @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; + } - // Divide [prod1 prod0] by twos. - prod0 := div(prod0, twos) + /** + * @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 == 0 ? 0 : (a - 1) / b + 1; + } - // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. - twos := add(div(sub(0, twos), twos), 1) - } + /** + * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 + * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) + * with further edits by Uniswap Labs also under MIT license. + */ + function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { + unchecked { + // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use + // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 + // variables such that product = prod1 * 2^256 + prod0. + uint256 prod0; // Least significant 256 bits of the product + uint256 prod1; // Most significant 256 bits of the product + assembly { + let mm := mulmod(x, y, not(0)) + prod0 := mul(x, y) + prod1 := sub(sub(mm, prod0), lt(mm, prod0)) + } - // Shift in bits from prod1 into prod0. - prod0 |= prod1 * twos; - - // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such - // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for - // four bits. That is, denominator * inv = 1 mod 2^4. - uint256 inverse = (3 * denominator) ^ 2; - - // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works - // in modular arithmetic, doubling the correct bits in each step. - inverse *= 2 - denominator * inverse; // inverse mod 2^8 - inverse *= 2 - denominator * inverse; // inverse mod 2^16 - inverse *= 2 - denominator * inverse; // inverse mod 2^32 - inverse *= 2 - denominator * inverse; // inverse mod 2^64 - inverse *= 2 - denominator * inverse; // inverse mod 2^128 - inverse *= 2 - denominator * inverse; // inverse mod 2^256 - - // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. - // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is - // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 - // is no longer required. - result = prod0 * inverse; - return result; + // Handle non-overflow cases, 256 by 256 division. + if (prod1 == 0) { + // Solidity will revert if denominator == 0, unlike the div opcode on its own. + // The surrounding unchecked block does not change this fact. + // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. + return prod0 / denominator; } - } - /** - * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { - uint256 result = mulDiv(x, y, denominator); - if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { - result += 1; + // Make sure the result is less than 2^256. Also prevents denominator == 0. + require(denominator > prod1, "Math: mulDiv overflow"); + + /////////////////////////////////////////////// + // 512 by 256 division. + /////////////////////////////////////////////// + + // Make division exact by subtracting the remainder from [prod1 prod0]. + uint256 remainder; + assembly { + // Compute remainder using mulmod. + remainder := mulmod(x, y, denominator) + + // Subtract 256 bit number from 512 bit number. + prod1 := sub(prod1, gt(remainder, prod0)) + prod0 := sub(prod0, remainder) + } + + // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. + // See https://cs.stackexchange.com/q/138556/92363. + + // Does not overflow because the denominator cannot be zero at this stage in the function. + uint256 twos = denominator & (~denominator + 1); + assembly { + // Divide denominator by twos. + denominator := div(denominator, twos) + + // Divide [prod1 prod0] by twos. + prod0 := div(prod0, twos) + + // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. + twos := add(div(sub(0, twos), twos), 1) } + + // Shift in bits from prod1 into prod0. + prod0 |= prod1 * twos; + + // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such + // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for + // four bits. That is, denominator * inv = 1 mod 2^4. + uint256 inverse = (3 * denominator) ^ 2; + + // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works + // in modular arithmetic, doubling the correct bits in each step. + inverse *= 2 - denominator * inverse; // inverse mod 2^8 + inverse *= 2 - denominator * inverse; // inverse mod 2^16 + inverse *= 2 - denominator * inverse; // inverse mod 2^32 + inverse *= 2 - denominator * inverse; // inverse mod 2^64 + inverse *= 2 - denominator * inverse; // inverse mod 2^128 + inverse *= 2 - denominator * inverse; // inverse mod 2^256 + + // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. + // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is + // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 + // is no longer required. + result = prod0 * inverse; return result; } + } - /** - * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. - * - * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). - */ - function sqrt(uint256 a) internal pure returns (uint256) { - if (a == 0) { - return 0; - } + /** + * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. + */ + function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { + uint256 result = mulDiv(x, y, denominator); + if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { + result += 1; + } + return result; + } - // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. - // - // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have - // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. - // - // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` - // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` - // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` - // - // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. - uint256 result = 1 << (log2(a) >> 1); - - // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, - // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at - // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision - // into the expected uint128 result. - unchecked { - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - return min(result, a / result); - } + /** + * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. + * + * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). + */ + function sqrt(uint256 a) internal pure returns (uint256) { + if (a == 0) { + return 0; } - /** - * @notice Calculates sqrt(a), following the selected rounding direction. - */ - function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = sqrt(a); - return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); - } + // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. + // + // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have + // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. + // + // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` + // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` + // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` + // + // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. + uint256 result = 1 << (log2(a) >> 1); + + // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, + // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at + // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision + // into the expected uint128 result. + unchecked { + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + result = (result + a / result) >> 1; + return min(result, a / result); } + } - /** - * @dev Return the log in base 2, rounded down, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 128; - } - if (value >> 64 > 0) { - value >>= 64; - result += 64; - } - if (value >> 32 > 0) { - value >>= 32; - result += 32; - } - if (value >> 16 > 0) { - value >>= 16; - result += 16; - } - if (value >> 8 > 0) { - value >>= 8; - result += 8; - } - if (value >> 4 > 0) { - value >>= 4; - result += 4; - } - if (value >> 2 > 0) { - value >>= 2; - result += 2; - } - if (value >> 1 > 0) { - result += 1; - } - } - return result; + /** + * @notice Calculates sqrt(a), following the selected rounding direction. + */ + function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = sqrt(a); + return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } + } - /** - * @dev Return the log in base 2, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log2(value); - return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); + /** + * @dev Return the log in base 2, rounded down, of a positive value. + * Returns 0 if given 0. + */ + function log2(uint256 value) internal pure returns (uint256) { + uint256 result = 0; + unchecked { + if (value >> 128 > 0) { + value >>= 128; + result += 128; + } + if (value >> 64 > 0) { + value >>= 64; + result += 64; + } + if (value >> 32 > 0) { + value >>= 32; + result += 32; + } + if (value >> 16 > 0) { + value >>= 16; + result += 16; + } + if (value >> 8 > 0) { + value >>= 8; + result += 8; + } + if (value >> 4 > 0) { + value >>= 4; + result += 4; + } + if (value >> 2 > 0) { + value >>= 2; + result += 2; + } + if (value >> 1 > 0) { + result += 1; } } + return result; + } - /** - * @dev Return the log in base 10, rounded down, of a positive value. - * Returns 0 if given 0. - */ - function log10(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >= 10 ** 64) { - value /= 10 ** 64; - result += 64; - } - if (value >= 10 ** 32) { - value /= 10 ** 32; - result += 32; - } - if (value >= 10 ** 16) { - value /= 10 ** 16; - result += 16; - } - if (value >= 10 ** 8) { - value /= 10 ** 8; - result += 8; - } - if (value >= 10 ** 4) { - value /= 10 ** 4; - result += 4; - } - if (value >= 10 ** 2) { - value /= 10 ** 2; - result += 2; - } - if (value >= 10 ** 1) { - result += 1; - } - } - return result; + /** + * @dev Return the log in base 2, following the selected rounding direction, of a positive value. + * Returns 0 if given 0. + */ + function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = log2(value); + return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } + } - /** - * @dev Return the log in base 10, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log10(value); - return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); + /** + * @dev Return the log in base 10, rounded down, of a positive value. + * Returns 0 if given 0. + */ + function log10(uint256 value) internal pure returns (uint256) { + uint256 result = 0; + unchecked { + if (value >= 10 ** 64) { + value /= 10 ** 64; + result += 64; + } + if (value >= 10 ** 32) { + value /= 10 ** 32; + result += 32; + } + if (value >= 10 ** 16) { + value /= 10 ** 16; + result += 16; + } + if (value >= 10 ** 8) { + value /= 10 ** 8; + result += 8; + } + if (value >= 10 ** 4) { + value /= 10 ** 4; + result += 4; + } + if (value >= 10 ** 2) { + value /= 10 ** 2; + result += 2; + } + if (value >= 10 ** 1) { + result += 1; } } + return result; + } - /** - * @dev Return the log in base 256, rounded down, of a positive value. - * Returns 0 if given 0. - * - * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. - */ - function log256(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 16; - } - if (value >> 64 > 0) { - value >>= 64; - result += 8; - } - if (value >> 32 > 0) { - value >>= 32; - result += 4; - } - if (value >> 16 > 0) { - value >>= 16; - result += 2; - } - if (value >> 8 > 0) { - result += 1; - } - } - return result; + /** + * @dev Return the log in base 10, following the selected rounding direction, of a positive value. + * Returns 0 if given 0. + */ + function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = log10(value); + return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } + } - /** - * @dev Return the log in base 256, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log256(value); - return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); + /** + * @dev Return the log in base 256, rounded down, of a positive value. + * Returns 0 if given 0. + * + * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. + */ + function log256(uint256 value) internal pure returns (uint256) { + uint256 result = 0; + unchecked { + if (value >> 128 > 0) { + value >>= 128; + result += 16; + } + if (value >> 64 > 0) { + value >>= 64; + result += 8; + } + if (value >> 32 > 0) { + value >>= 32; + result += 4; + } + if (value >> 16 > 0) { + value >>= 16; + result += 2; + } + if (value >> 8 > 0) { + result += 1; } } + return result; } - // src/interfaces/IBaseStrategy.sol - - interface IBaseStrategy { - function tokenizedStrategyAddress() external view returns (address); - - /*////////////////////////////////////////////////////////////// - IMMUTABLE FUNCTIONS - //////////////////////////////////////////////////////////////*/ - - function availableDepositLimit( - address _owner - ) external view returns (uint256); - - function availableWithdrawLimit( - address _owner - ) external view returns (uint256); + /** + * @dev Return the log in base 256, following the selected rounding direction, of a positive value. + * Returns 0 if given 0. + */ + function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { + unchecked { + uint256 result = log256(value); + return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); + } + } +} - function deployFunds(uint256 _assets) external; +// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol - function freeFunds(uint256 _amount) external; +// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) - function harvestAndReport() external returns (uint256); +/** + * @dev Interface for the optional metadata functions from the ERC20 standard. + * + * _Available since v4.1._ + */ +interface IERC20Metadata is IERC20 { + /** + * @dev Returns the name of the token. + */ + function name() external view returns (string memory); - function tendThis(uint256 _totalIdle) external; + /** + * @dev Returns the symbol of the token. + */ + function symbol() external view returns (string memory); - function shutdownWithdraw(uint256 _amount) external; + /** + * @dev Returns the decimals places of the token. + */ + function decimals() external view returns (uint8); +} + +// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol + +// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.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.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How + * to implement supply mechanisms]. + * + * The default value of {decimals} is 18. To change this, you should override + * this function so it returns a different value. + * + * 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 ERC20 is Context, IERC20, IERC20Metadata { + mapping(address => uint256) private _balances; + + mapping(address => mapping(address => uint256)) private _allowances; + + uint256 private _totalSupply; + + string private _name; + string private _symbol; - function tendTrigger() external view returns (bool, bytes memory); + /** + * @dev Sets the values for {name} and {symbol}. + * + * All two of these values are immutable: they can only be set once during + * construction. + */ + constructor(string memory name_, string memory symbol_) { + _name = name_; + _symbol = symbol_; } - // src/interfaces/IFactory.sol + /** + * @dev Returns the name of the token. + */ + function name() public view virtual override returns (string memory) { + return _name; + } - interface IFactory { - function protocol_fee_config() external view returns (uint16, address); + /** + * @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; } - // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol + /** + * @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 default value returned by this function, unless + * it's 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; + } - // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) + /** + * @dev See {IERC20-totalSupply}. + */ + function totalSupply() public view virtual override returns (uint256) { + return _totalSupply; + } /** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ - interface IERC20Metadata is IERC20 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); + * @dev See {IERC20-balanceOf}. + */ + function balanceOf(address account) public view virtual override returns (uint256) { + return _balances[account]; + } - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); + /** + * @dev See {IERC20-transfer}. + * + * Requirements: + * + * - `to` cannot be the zero address. + * - the caller must have a balance of at least `amount`. + */ + function transfer(address to, uint256 amount) public virtual override returns (bool) { + address owner = _msgSender(); + _transfer(owner, to, amount); + return true; + } - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); + /** + * @dev See {IERC20-allowance}. + */ + function allowance(address owner, address spender) public view virtual override returns (uint256) { + return _allowances[owner][spender]; } - // lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol + /** + * @dev See {IERC20-approve}. + * + * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on + * `transferFrom`. This is semantically equivalent to an infinite approval. + * + * Requirements: + * + * - `spender` cannot be the zero address. + */ + function approve(address spender, uint256 amount) public virtual override returns (bool) { + address owner = _msgSender(); + _approve(owner, spender, amount); + return true; + } - // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) + /** + * @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}. + * + * NOTE: Does not update the allowance if the current allowance + * is the maximum `uint256`. + * + * Requirements: + * + * - `from` and `to` cannot be the zero address. + * - `from` must have a balance of at least `amount`. + * - the caller must have allowance for ``from``'s tokens of at least + * `amount`. + */ + function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { + address spender = _msgSender(); + _spendAllowance(from, spender, amount); + _transfer(from, to, amount); + return true; + } /** - * @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.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * The default value of {decimals} is 18. To change this, you should override - * this function so it returns a different value. - * - * 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 ERC20 is Context, IERC20, IERC20Metadata { - mapping(address => uint256) private _balances; + * @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) { + address owner = _msgSender(); + _approve(owner, spender, allowance(owner, spender) + addedValue); + return true; + } - mapping(address => mapping(address => uint256)) private _allowances; + /** + * @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) { + address owner = _msgSender(); + uint256 currentAllowance = allowance(owner, spender); + require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); + unchecked { + _approve(owner, spender, currentAllowance - subtractedValue); + } + + return true; + } - uint256 private _totalSupply; + /** + * @dev Moves `amount` of tokens from `from` to `to`. + * + * 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: + * + * - `from` cannot be the zero address. + * - `to` cannot be the zero address. + * - `from` must have a balance of at least `amount`. + */ + function _transfer(address from, address to, uint256 amount) internal virtual { + require(from != address(0), "ERC20: transfer from the zero address"); + require(to != address(0), "ERC20: transfer to the zero address"); + + _beforeTokenTransfer(from, to, amount); + + uint256 fromBalance = _balances[from]; + require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); + unchecked { + _balances[from] = fromBalance - amount; + // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by + // decrementing then incrementing. + _balances[to] += amount; + } + + emit Transfer(from, to, amount); + + _afterTokenTransfer(from, to, amount); + } - string private _name; - string private _symbol; + /** @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"); - /** - * @dev Sets the values for {name} and {symbol}. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } + _beforeTokenTransfer(address(0), account, amount); - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; + _totalSupply += amount; + unchecked { + // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. + _balances[account] += amount; } + emit Transfer(address(0), account, amount); - /** - * @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; - } + _afterTokenTransfer(address(0), account, amount); + } - /** - * @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 default value returned by this function, unless - * it's 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 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; + // Overflow not possible: amount <= accountBalance <= totalSupply. + _totalSupply -= amount; + } + + emit Transfer(account, address(0), amount); + + _afterTokenTransfer(account, address(0), amount); + } - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } + /** + * @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 See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account]; + /** + * @dev Updates `owner` s allowance for `spender` based on spent `amount`. + * + * Does not update the allowance amount in case of infinite allowance. + * Revert if not enough allowance is available. + * + * Might emit an {Approval} event. + */ + function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { + uint256 currentAllowance = allowance(owner, spender); + if (currentAllowance != type(uint256).max) { + require(currentAllowance >= amount, "ERC20: insufficient allowance"); + unchecked { + _approve(owner, spender, currentAllowance - amount); + } } + } - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address to, uint256 amount) public virtual override returns (bool) { - address owner = _msgSender(); - _transfer(owner, to, amount); - return true; - } + /** + * @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 See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } + /** + * @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 {} +} + +// lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol + +// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure (when the token + * contract returns false). Tokens that return no value (and instead revert or + * throw on failure) are also supported, non-reverting calls are assumed to be + * successful. + * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + using Address for address; - /** - * @dev See {IERC20-approve}. - * - * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on - * `transferFrom`. This is semantically equivalent to an infinite approval. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, amount); - return true; - } + /** + * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, + * non-reverting calls are assumed to be successful. + */ + function safeTransfer(IERC20 token, address to, uint256 value) internal { + _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); + } - /** - * @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}. - * - * NOTE: Does not update the allowance if the current allowance - * is the maximum `uint256`. - * - * Requirements: - * - * - `from` and `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - * - the caller must have allowance for ``from``'s tokens of at least - * `amount`. - */ - function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { - address spender = _msgSender(); - _spendAllowance(from, spender, amount); - _transfer(from, to, amount); - return true; - } + /** + * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the + * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. + */ + function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { + _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); + } - /** - * @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) { - address owner = _msgSender(); - _approve(owner, spender, allowance(owner, spender) + addedValue); - return true; - } + /** + * @dev Deprecated. This function has issues similar to the ones found in + * {IERC20-approve}, and its usage is discouraged. + * + * Whenever possible, use {safeIncreaseAllowance} and + * {safeDecreaseAllowance} instead. + */ + function safeApprove(IERC20 token, address spender, uint256 value) internal { + // safeApprove should only be called when setting an initial allowance, + // or when resetting it to zero. To increase and decrease it, use + // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' + 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)); + } - /** - * @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) { - address owner = _msgSender(); - uint256 currentAllowance = allowance(owner, spender); - require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); - unchecked { - _approve(owner, spender, currentAllowance - subtractedValue); - } + /** + * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, + * non-reverting calls are assumed to be successful. + */ + function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { + uint256 oldAllowance = token.allowance(address(this), spender); + _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); + } - return true; + /** + * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, + * non-reverting calls are assumed to be successful. + */ + function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { + unchecked { + uint256 oldAllowance = token.allowance(address(this), spender); + require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); + _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } + } - /** - * @dev Moves `amount` of tokens from `from` to `to`. - * - * 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: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - */ - function _transfer(address from, address to, uint256 amount) internal virtual { - require(from != address(0), "ERC20: transfer from the zero address"); - require(to != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(from, to, amount); - - uint256 fromBalance = _balances[from]; - require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[from] = fromBalance - amount; - // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by - // decrementing then incrementing. - _balances[to] += amount; - } - - emit Transfer(from, to, amount); + /** + * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, + * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval + * to be set to zero before setting it to a non-zero value, such as USDT. + */ + function forceApprove(IERC20 token, address spender, uint256 value) internal { + bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); - _afterTokenTransfer(from, to, amount); + if (!_callOptionalReturnBool(token, approvalCall)) { + _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); + _callOptionalReturn(token, approvalCall); } + } - /** @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; - unchecked { - // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. - _balances[account] += amount; - } - emit Transfer(address(0), account, amount); + /** + * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. + * Revert on invalid signature. + */ + function safePermit( + IERC20Permit token, + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) internal { + uint256 nonceBefore = token.nonces(owner); + token.permit(owner, spender, value, deadline, v, r, s); + uint256 nonceAfter = token.nonces(owner); + require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); + } - _afterTokenTransfer(address(0), account, amount); - } + /** + * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement + * on the return value: the return value is optional (but if data is returned, it must not be false). + * @param token The token targeted by the call. + * @param data The call data (encoded using abi.encode or one of its variants). + */ + function _callOptionalReturn(IERC20 token, bytes memory data) private { + // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since + // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that + // the target address contains contract code and also asserts for success in the low-level call. + + bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); + require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); + } - /** - * @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; - // Overflow not possible: amount <= accountBalance <= totalSupply. - _totalSupply -= amount; - } + /** + * @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). + * + * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. + */ + function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { + // 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 cannot use {Address-functionCall} here since this should return false + // and not revert is the subcall reverts. + + (bool success, bytes memory returndata) = address(token).call(data); + return + success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); + } +} + +// src/TokenizedStrategy.sol + +/**$$$$$$$$$$$$$$$$$$$$$$$$$$$&Mr/|1+~>>iiiiiiiiiii>~+{|tuMW$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$$$$$$$$$$B#j]->iiiiiiiiiiiiiiiiiiiiiiiiiiii>-?f*B$$$$$$$$$$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$$$$$$@zj}~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~}fv@$$$$$$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$$$@z(+iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii+)zB$$$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$Mf~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~t#@$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$@u[iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii?n@$$$$$$$$$$$$$ +$$$$$$$$$$$@z]iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii?u@$$$$$$$$$$$ +$$$$$$$$$$v]iiiiiiiiiiiiiiii,.';iiiiiiiiiiiiiiiiiiiiiiiiii;'."iiiiiiiiiiiiiiii?u$$$$$$$$$$ +$$$$$$$$%)>iiiiiiiiiiiiiii,. ';iiiiiiiiiiiiiiiiiiiiii;' ."iiiiiiiiiiiiiiii1%$$$$$$$$ +$$$$$$$c~iiiiiiiiiiiiiii,. ';iiiiiiiiiiiiiiiiii;' ."iiiiiiiiiiiiiii~u$$$$$$$ +$$$$$B/>iiiiiiiiiiiiii!' `IiiiiiiiiiiiiiiI` .Iiiiiiiiiiiiiii>|%$$$$$ +$$$$@)iiiiiiiiiiiiiiiii;' `Iiiiiiiiiiil` ';iiiiiiiiiiiiiiiii}@$$$$ +$$$B|iiiiiiiiiiiiiiiiiiii;' `Iiiiiiil` ';iiiiiiiiiiiiiiiiiiii1B$$$ +$$@)iiiiiiiiiiiiiiiiiiiiiii:' `;iiI` ':iiiiiiiiiiiiiiiiiiiiiii{B$$ +$$|iiiiiiiiiiiiiiiiiiiiiiiiii;' `` ':iiiiiiiiiiiiiiiiiiiiiiiiii1$$ +$v>iiiiiiiiiiiiiiiiiiiiiiiiiiii:' ':iiiiiiiiiiiiiiiiiiiiiiiiiiii>x$ +&?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:' .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-W +ziiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:' .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiv +-iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:' .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii- +iiiiiiiiiiiiiiiiii. `!iiiiiiiiiiiiiiiiiiiiiii^ .liiiiiiiiiiiiiiiiiir$ +$$(iiiiiiiiiiiiiiiiii;. ."iiiiiiiiiiiiiiiiiiii,. :iiiiiiiiiiiiiiiiii}$$ +$$@{iiiiiiiiiiiiiiiiii;. .`:iiiiiiiiiiiiii;^. :iiiiiiiiiiiiiiiiii}B$$ +$$$B)iiiiiiiiiiiiiiiiii!' '`",::::,"`'. .Iiiiiiiiiiiiiiiiiii{%$$$ +$$$$@1iiiiiiiiiiiiiiiiiii,. ^iiiiiiiiiiiiiiiiiii[@$$$$ +$$$$$B|>iiiiiiiiiiiiiiiiii!^. `liiiiiiiiiiiiiiiiii>)%$$$$$ +$$$$$$$c~iiiiiiiiiiiiiiiiiiii"' ."!iiiiiiiiiiiiiiiiiii~n$$$$$$$ +$$$$$$$$B)iiiiiiiiiiiiiiiiiiiii!,`. .'"liiiiiiiiiiiiiiiiiiiii1%$$$$$$$$ +$$$$$$$$$@u]iiiiiiiiiiiiiiiiiiiiiiil,^`'.. ..''^,liiiiiiiiiiiiiiiiiiiiiii-x@$$$$$$$$$ +$$$$$$$$$$$@v?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-x$$$$$$$$$$$$ +$$$$$$$$$$$$$@n?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-rB$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$/~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii<\*@$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$$$Bc1~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~{v%$$$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$$$$$$Bvf]iiiiiiiiiiiiiiiiiiiiiiiiiiiii+_tc%$$$$$$$$$$$$$$$$$$$$$$$$$ +$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$W#u/|{+~>iiiiiiiiiiii><+{|/n#W$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/ + +/** + * @title Yearn Tokenized Strategy + * @author yearn.finance + * @notice + * This TokenizedStrategy can be used by anyone wishing to easily build + * and deploy their own custom ERC4626 compliant single strategy Vault. + * + * The TokenizedStrategy contract is meant to be used as the proxy + * implementation contract that will handle all logic, storage and + * management for a custom strategy that inherits the `BaseStrategy`. + * Any function calls to the strategy that are not defined within that + * strategy will be forwarded through a delegateCall to this contract. + * + * A strategist only needs to override a few simple functions that are + * focused entirely on the strategy specific needs to easily and cheaply + * deploy their own permissionless 4626 compliant vault. + */ +contract TokenizedStrategy { + using Math for uint256; + using SafeERC20 for ERC20; + + /*////////////////////////////////////////////////////////////// + EVENTS + //////////////////////////////////////////////////////////////*/ + /** + * @notice Emitted when a strategy is shutdown. + */ + event StrategyShutdown(); - emit Transfer(account, address(0), amount); + /** + * @notice Emitted when a strategies paused status is updated. + */ + event UpdatePaused(bool paused); - _afterTokenTransfer(account, address(0), amount); - } + /** + * @notice Emitted on the initialization of any new `strategy` that uses `asset` + * with this specific `apiVersion`. + */ + event NewTokenizedStrategy( + address indexed strategy, + address indexed asset, + string apiVersion + ); - /** - * @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); - } + /** + * @notice Emitted when the strategy reports `profit` or `loss` and + * `performanceFees` and `protocolFees` are paid out. + */ + event Reported( + uint256 profit, + uint256 loss, + uint256 protocolFees, + uint256 performanceFees + ); - /** - * @dev Updates `owner` s allowance for `spender` based on spent `amount`. - * - * Does not update the allowance amount in case of infinite allowance. - * Revert if not enough allowance is available. - * - * Might emit an {Approval} event. - */ - function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance != type(uint256).max) { - require(currentAllowance >= amount, "ERC20: insufficient allowance"); - unchecked { - _approve(owner, spender, currentAllowance - amount); - } - } - } + /** + * @notice Emitted when the strategy accrues `profit` or `loss` outside of + * an explicit report and `performanceFees` and `protocolFees` are paid out. + */ + event Accrued( + uint256 profit, + uint256 loss, + uint256 protocolFees, + uint256 performanceFees + ); - /** - * @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 {} - } - - // lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol - - // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) - - /** - * @title SafeERC20 - * @dev Wrappers around ERC20 operations that throw on failure (when the token - * contract returns false). Tokens that return no value (and instead revert or - * throw on failure) are also supported, non-reverting calls are assumed to be - * successful. - * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, - * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. - */ - library SafeERC20 { - using Address for address; - - /** - * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeTransfer(IERC20 token, address to, uint256 value) internal { - _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); - } + /** + * @notice Emitted when the 'performanceFeeRecipient' address is + * updated to 'newPerformanceFeeRecipient'. + */ + event UpdatePerformanceFeeRecipient( + address indexed newPerformanceFeeRecipient + ); - /** - * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the - * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. - */ - function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { - _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); - } + /** + * @notice Emitted when the 'keeper' address is updated to 'newKeeper'. + */ + event UpdateKeeper(address indexed newKeeper); - /** - * @dev Deprecated. This function has issues similar to the ones found in - * {IERC20-approve}, and its usage is discouraged. - * - * Whenever possible, use {safeIncreaseAllowance} and - * {safeDecreaseAllowance} instead. - */ - function safeApprove(IERC20 token, address spender, uint256 value) internal { - // safeApprove should only be called when setting an initial allowance, - // or when resetting it to zero. To increase and decrease it, use - // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' - 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)); - } + /** + * @notice Emitted when the 'performanceFee' is updated to 'newPerformanceFee'. + */ + event UpdatePerformanceFee(uint16 newPerformanceFee); - /** - * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { - uint256 oldAllowance = token.allowance(address(this), spender); - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); - } + /** + * @notice Emitted when the 'management' address is updated to 'newManagement'. + */ + event UpdateManagement(address indexed newManagement); - /** - * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { - unchecked { - uint256 oldAllowance = token.allowance(address(this), spender); - require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); - } - } + /** + * @notice Emitted when the 'emergencyAdmin' address is updated to 'newEmergencyAdmin'. + */ + event UpdateEmergencyAdmin(address indexed newEmergencyAdmin); - /** - * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval - * to be set to zero before setting it to a non-zero value, such as USDT. - */ - function forceApprove(IERC20 token, address spender, uint256 value) internal { - bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); - - if (!_callOptionalReturnBool(token, approvalCall)) { - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); - _callOptionalReturn(token, approvalCall); - } - } + /** + * @notice Emitted when the 'profitMaxUnlockTime' is updated to 'newProfitMaxUnlockTime'. + */ + event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime); - /** - * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. - * Revert on invalid signature. - */ - function safePermit( - IERC20Permit token, - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) internal { - uint256 nonceBefore = token.nonces(owner); - token.permit(owner, spender, value, deadline, v, r, s); - uint256 nonceAfter = token.nonces(owner); - require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); - } + /** + * @notice Emitted when the 'pendingManagement' address is updated to 'newPendingManagement'. + */ + event UpdatePendingManagement(address indexed newPendingManagement); - /** - * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement - * on the return value: the return value is optional (but if data is returned, it must not be false). - * @param token The token targeted by the call. - * @param data The call data (encoded using abi.encode or one of its variants). - */ - function _callOptionalReturn(IERC20 token, bytes memory data) private { - // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since - // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that - // the target address contains contract code and also asserts for success in the low-level call. - - bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); - require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); - } + /** + * @notice 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 + ); - /** - * @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). - * - * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. - */ - function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { - // 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 cannot use {Address-functionCall} here since this should return false - // and not revert is the subcall reverts. - - (bool success, bytes memory returndata) = address(token).call(data); - return - success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); - } + /** + * @notice 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); + + /** + * @notice Emitted when the `caller` has exchanged `assets` for `shares`, + * and transferred those `shares` to `owner`. + */ + event Deposit( + address indexed caller, + address indexed owner, + uint256 assets, + uint256 shares + ); + + /** + * @notice Emitted when the `caller` has exchanged `owner`s `shares` for `assets`, + * and transferred those `assets` to `receiver`. + */ + event Withdraw( + address indexed caller, + address indexed receiver, + address indexed owner, + uint256 assets, + uint256 shares + ); + + /*////////////////////////////////////////////////////////////// + STORAGE STRUCT + //////////////////////////////////////////////////////////////*/ + + /** + * @dev The struct that will hold all the storage data for each strategy + * that uses this implementation. + * + * This replaces all state variables for a traditional contract. This + * full struct will be initialized on the creation of the strategy + * and continually updated and read from for the life of the contract. + * + * We combine all the variables into one struct to limit the amount of + * times the custom storage slots need to be loaded during complex functions. + * + * Loading the corresponding storage slot for the struct does not + * load any of the contents of the struct into memory. So the size + * will not increase memory related gas usage. + */ + // prettier-ignore + struct StrategyData { + // The ERC20 compliant underlying asset that will be + // used by the Strategy + ERC20 asset; + + // These are the corresponding ERC20 variables needed for the + // strategies token that is issued and burned on each deposit or withdraw. + uint8 decimals; // The amount of decimals that `asset` and strategy use. + string name; // The name of the token for the strategy. + uint256 totalSupply; // The total amount of shares currently issued. + mapping(address => uint256) nonces; // Mapping of nonces used for permit functions. + mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares. + mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. + + // Last realized total assets. This is used as the accrual baseline during + // write flows and to freeze view math during in-flight external callbacks. + uint256 lastTotalAssets; + + // Variables for profit reporting and locking. + // We use uint96 for timestamps to fit in the same slot as an address. That overflows in 2.5e+21 years. + // I know Yearn moves slowly but surely V4 will be out by then. + // If the timestamps ever overflow tell the cyborgs still using this code I'm sorry for being cheap. + uint256 profitUnlockingRate; // The rate at which locked profit is unlocking. + uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock. + address keeper; // Address given permission to call {report} and {tend}. + uint32 profitMaxUnlockTime; + uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. + address performanceFeeRecipient; // The address to pay the `performanceFee` to. + uint96 lastReport; // The last time a report updated the lock schedule. + + // Access management variables. + address management; // Main address that can set all configurable variables. + address pendingManagement; // Address that is pending to take over `management`. + address emergencyAdmin; // Address to act in emergencies as well as `management`. + + // Strategy Status + uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. + bool shutdown; // Bool that can be used to stop deposits into the strategy. + bool paused; // Bool that can be used to stop user facing 4626 functions. + + uint72 lastAccrual; // The last time accounting synced. } - // src/TokenizedStrategy.sol - - /**$$$$$$$$$$$$$$$$$$$$$$$$$$$&Mr/|1+~>>iiiiiiiiiii>~+{|tuMW$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$$$$$$$$$$B#j]->iiiiiiiiiiiiiiiiiiiiiiiiiiii>-?f*B$$$$$$$$$$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$$$$$$@zj}~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~}fv@$$$$$$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$$$@z(+iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii+)zB$$$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$Mf~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~t#@$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$@u[iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii?n@$$$$$$$$$$$$$ - $$$$$$$$$$$@z]iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii?u@$$$$$$$$$$$ - $$$$$$$$$$v]iiiiiiiiiiiiiiii,.';iiiiiiiiiiiiiiiiiiiiiiiiii;'."iiiiiiiiiiiiiiii?u$$$$$$$$$$ - $$$$$$$$%)>iiiiiiiiiiiiiii,. ';iiiiiiiiiiiiiiiiiiiiii;' ."iiiiiiiiiiiiiiii1%$$$$$$$$ - $$$$$$$c~iiiiiiiiiiiiiii,. ';iiiiiiiiiiiiiiiiii;' ."iiiiiiiiiiiiiii~u$$$$$$$ - $$$$$B/>iiiiiiiiiiiiii!' `IiiiiiiiiiiiiiiI` .Iiiiiiiiiiiiiii>|%$$$$$ - $$$$@)iiiiiiiiiiiiiiiii;' `Iiiiiiiiiiil` ';iiiiiiiiiiiiiiiii}@$$$$ - $$$B|iiiiiiiiiiiiiiiiiiii;' `Iiiiiiil` ';iiiiiiiiiiiiiiiiiiii1B$$$ - $$@)iiiiiiiiiiiiiiiiiiiiiii:' `;iiI` ':iiiiiiiiiiiiiiiiiiiiiii{B$$ - $$|iiiiiiiiiiiiiiiiiiiiiiiiii;' `` ':iiiiiiiiiiiiiiiiiiiiiiiiii1$$ - $v>iiiiiiiiiiiiiiiiiiiiiiiiiiii:' ':iiiiiiiiiiiiiiiiiiiiiiiiiiii>x$ - &?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:' .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-W - ziiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:' .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiv - -iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:' .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii- - iiiiiiiiiiiiiiiiii. `!iiiiiiiiiiiiiiiiiiiiiii^ .liiiiiiiiiiiiiiiiiir$ - $$(iiiiiiiiiiiiiiiiii;. ."iiiiiiiiiiiiiiiiiiii,. :iiiiiiiiiiiiiiiiii}$$ - $$@{iiiiiiiiiiiiiiiiii;. .`:iiiiiiiiiiiiii;^. :iiiiiiiiiiiiiiiiii}B$$ - $$$B)iiiiiiiiiiiiiiiiii!' '`",::::,"`'. .Iiiiiiiiiiiiiiiiiii{%$$$ - $$$$@1iiiiiiiiiiiiiiiiiii,. ^iiiiiiiiiiiiiiiiiii[@$$$$ - $$$$$B|>iiiiiiiiiiiiiiiiii!^. `liiiiiiiiiiiiiiiiii>)%$$$$$ - $$$$$$$c~iiiiiiiiiiiiiiiiiiii"' ."!iiiiiiiiiiiiiiiiiii~n$$$$$$$ - $$$$$$$$B)iiiiiiiiiiiiiiiiiiiii!,`. .'"liiiiiiiiiiiiiiiiiiiii1%$$$$$$$$ - $$$$$$$$$@u]iiiiiiiiiiiiiiiiiiiiiiil,^`'.. ..''^,liiiiiiiiiiiiiiiiiiiiiii-x@$$$$$$$$$ - $$$$$$$$$$$@v?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-x$$$$$$$$$$$$ - $$$$$$$$$$$$$@n?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-rB$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$/~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii<\*@$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$$$Bc1~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~{v%$$$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$$$$$$Bvf]iiiiiiiiiiiiiiiiiiiiiiiiiiiii+_tc%$$$$$$$$$$$$$$$$$$$$$$$$$ - $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$W#u/|{+~>iiiiiiiiiiii><+{|/n#W$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/ - - /** - * @title Yearn Tokenized Strategy - * @author yearn.finance - * @notice - * This TokenizedStrategy can be used by anyone wishing to easily build - * and deploy their own custom ERC4626 compliant single strategy Vault. - * - * The TokenizedStrategy contract is meant to be used as the proxy - * implementation contract that will handle all logic, storage and - * management for a custom strategy that inherits the `BaseStrategy`. - * Any function calls to the strategy that are not defined within that - * strategy will be forwarded through a delegateCall to this contract. - - * A strategist only needs to override a few simple functions that are - * focused entirely on the strategy specific needs to easily and cheaply - * deploy their own permissionless 4626 compliant vault. - */ - contract TokenizedStrategy { - using Math for uint256; - using SafeERC20 for ERC20; - - /*////////////////////////////////////////////////////////////// - EVENTS - //////////////////////////////////////////////////////////////*/ - /** - * @notice Emitted when a strategy is shutdown. - */ - event StrategyShutdown(); - - /** - * @notice Emitted on the initialization of any new `strategy` that uses `asset` - * with this specific `apiVersion`. - */ - event NewTokenizedStrategy( - address indexed strategy, - address indexed asset, - string apiVersion - ); + /*////////////////////////////////////////////////////////////// + MODIFIERS + //////////////////////////////////////////////////////////////*/ - /** - * @notice Emitted when the strategy reports `profit` or `loss` and - * `performanceFees` and `protocolFees` are paid out. - */ - event Reported( - uint256 profit, - uint256 loss, - uint256 protocolFees, - uint256 performanceFees - ); + /** + * @dev Require that the call is coming from the strategies management. + */ + modifier onlyManagement() { + requireManagement(msg.sender); + _; + } - /** - * @notice Emitted when the 'performanceFeeRecipient' address is - * updated to 'newPerformanceFeeRecipient'. - */ - event UpdatePerformanceFeeRecipient( - address indexed newPerformanceFeeRecipient - ); + /** + * @dev Require that the call is coming from either the strategies + * management or the keeper. + */ + modifier onlyKeepers() { + requireKeeperOrManagement(msg.sender); + _; + } - /** - * @notice Emitted when the 'keeper' address is updated to 'newKeeper'. - */ - event UpdateKeeper(address indexed newKeeper); - - /** - * @notice Emitted when the 'performanceFee' is updated to 'newPerformanceFee'. - */ - event UpdatePerformanceFee(uint16 newPerformanceFee); - - /** - * @notice Emitted when the 'management' address is updated to 'newManagement'. - */ - event UpdateManagement(address indexed newManagement); - - /** - * @notice Emitted when the 'emergencyAdmin' address is updated to 'newEmergencyAdmin'. - */ - event UpdateEmergencyAdmin(address indexed newEmergencyAdmin); - - /** - * @notice Emitted when the 'profitMaxUnlockTime' is updated to 'newProfitMaxUnlockTime'. - */ - event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime); - - /** - * @notice Emitted when the 'pendingManagement' address is updated to 'newPendingManagement'. - */ - event UpdatePendingManagement(address indexed newPendingManagement); - - /** - * @notice 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 - ); + /** + * @dev Require that the call is coming from either the strategies + * management or the emergencyAdmin. + */ + modifier onlyEmergencyAuthorized() { + requireEmergencyAuthorized(msg.sender); + _; + } - /** - * @notice 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); - - /** - * @notice Emitted when the `caller` has exchanged `assets` for `shares`, - * and transferred those `shares` to `owner`. - */ - event Deposit( - address indexed caller, - address indexed owner, - uint256 assets, - uint256 shares - ); + /** + * @dev Prevents a contract from calling itself, directly or indirectly. + * Placed over all state changing functions for increased safety. + */ + modifier nonReentrant() { + StrategyData storage S = _strategyStorage(); + // On the first call to nonReentrant, `entered` will be false (2) + require(S.entered != ENTERED, "ReentrancyGuard: reentrant call"); - /** - * @notice Emitted when the `caller` has exchanged `owner`s `shares` for `assets`, - * and transferred those `assets` to `receiver`. - */ - event Withdraw( - address indexed caller, - address indexed receiver, - address indexed owner, - uint256 assets, - uint256 shares - ); + // Any calls to nonReentrant after this point will fail + S.entered = ENTERED; - /*////////////////////////////////////////////////////////////// - STORAGE STRUCT - //////////////////////////////////////////////////////////////*/ - - /** - * @dev The struct that will hold all the storage data for each strategy - * that uses this implementation. - * - * This replaces all state variables for a traditional contract. This - * full struct will be initialized on the creation of the strategy - * and continually updated and read from for the life of the contract. - * - * We combine all the variables into one struct to limit the amount of - * times the custom storage slots need to be loaded during complex functions. - * - * Loading the corresponding storage slot for the struct does not - * load any of the contents of the struct into memory. So the size - * will not increase memory related gas usage. - */ - // prettier-ignore - struct StrategyData { - // The ERC20 compliant underlying asset that will be - // used by the Strategy - ERC20 asset; - - // These are the corresponding ERC20 variables needed for the - // strategies token that is issued and burned on each deposit or withdraw. - uint8 decimals; // The amount of decimals that `asset` and strategy use. - string name; // The name of the token for the strategy. - uint256 totalSupply; // The total amount of shares currently issued. - mapping(address => uint256) nonces; // Mapping of nonces used for permit functions. - mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares. - mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares. - - // We manually track `totalAssets` to prevent PPS manipulation through airdrops. - uint256 totalAssets; - - // Variables for profit reporting and locking. - // We use uint96 for timestamps to fit in the same slot as an address. That overflows in 2.5e+21 years. - // I know Yearn moves slowly but surely V4 will be out by then. - // If the timestamps ever overflow tell the cyborgs still using this code I'm sorry for being cheap. - uint256 profitUnlockingRate; // The rate at which locked profit is unlocking. - uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock. - address keeper; // Address given permission to call {report} and {tend}. - uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over. - uint16 performanceFee; // The percent in basis points of profit that is charged as a fee. - address performanceFeeRecipient; // The address to pay the `performanceFee` to. - uint96 lastReport; // The last time a {report} was called. - - // Access management variables. - address management; // Main address that can set all configurable variables. - address pendingManagement; // Address that is pending to take over `management`. - address emergencyAdmin; // Address to act in emergencies as well as `management`. - - // Strategy Status - uint8 entered; // To prevent reentrancy. Use uint8 for gas savings. - bool shutdown; // Bool that can be used to stop deposits into the strategy. - } + _; - /*////////////////////////////////////////////////////////////// - MODIFIERS - //////////////////////////////////////////////////////////////*/ + // Reset to false (1) once call has finished. + S.entered = NOT_ENTERED; + } - /** - * @dev Require that the call is coming from the strategies management. - */ - modifier onlyManagement() { - requireManagement(msg.sender); - _; - } + /** + * @dev Require that the strategy is not paused. + */ + modifier whenNotPaused() { + require(!_strategyStorage().paused, "paused"); + _; + } - /** - * @dev Require that the call is coming from either the strategies - * management or the keeper. - */ - modifier onlyKeepers() { - requireKeeperOrManagement(msg.sender); - _; - } + /** + * @notice Require a caller is `management`. + * @dev Is left public so that it can be used by the Strategy. + * + * When the Strategy calls this the msg.sender would be the + * address of the strategy so we need to specify the sender. + * + * @param _sender The original msg.sender. + */ + function requireManagement(address _sender) public view { + require(_sender == _strategyStorage().management, "!management"); + } - /** - * @dev Require that the call is coming from either the strategies - * management or the emergencyAdmin. - */ - modifier onlyEmergencyAuthorized() { - requireEmergencyAuthorized(msg.sender); - _; - } + /** + * @notice Require a caller is the `keeper` or `management`. + * @dev Is left public so that it can be used by the Strategy. + * + * When the Strategy calls this the msg.sender would be the + * address of the strategy so we need to specify the sender. + * + * @param _sender The original msg.sender. + */ + function requireKeeperOrManagement(address _sender) public view { + StrategyData storage S = _strategyStorage(); + require(_sender == S.keeper || _sender == S.management, "!keeper"); + } - /** - * @dev Prevents a contract from calling itself, directly or indirectly. - * Placed over all state changing functions for increased safety. - */ - modifier nonReentrant() { - StrategyData storage S = _strategyStorage(); - // On the first call to nonReentrant, `entered` will be false (2) - require(S.entered != ENTERED, "ReentrancyGuard: reentrant call"); + /** + * @notice Require a caller is the `management` or `emergencyAdmin`. + * @dev Is left public so that it can be used by the Strategy. + * + * When the Strategy calls this the msg.sender would be the + * address of the strategy so we need to specify the sender. + * + * @param _sender The original msg.sender. + */ + function requireEmergencyAuthorized(address _sender) public view { + StrategyData storage S = _strategyStorage(); + require( + _sender == S.emergencyAdmin || _sender == S.management, + "!emergency authorized" + ); + } - // Any calls to nonReentrant after this point will fail - S.entered = ENTERED; + /*////////////////////////////////////////////////////////////// + CONSTANTS + //////////////////////////////////////////////////////////////*/ - _; + /// @notice API version this TokenizedStrategy implements. + string internal constant API_VERSION = "3.1.0"; - // Reset to false (1) once call has finished. - S.entered = NOT_ENTERED; - } + /// @notice Value to set the `entered` flag to during a call. + uint8 internal constant ENTERED = 2; + /// @notice Value to set the `entered` flag to at the end of the call. + uint8 internal constant NOT_ENTERED = 1; - /** - * @notice Require a caller is `management`. - * @dev Is left public so that it can be used by the Strategy. - * - * When the Strategy calls this the msg.sender would be the - * address of the strategy so we need to specify the sender. - * - * @param _sender The original msg.sender. - */ - function requireManagement(address _sender) public view { - require(_sender == _strategyStorage().management, "!management"); - } + /// @notice Maximum in Basis Points the Performance Fee can be set to. + uint16 public constant MAX_FEE = 5_000; // 50% - /** - * @notice Require a caller is the `keeper` or `management`. - * @dev Is left public so that it can be used by the Strategy. - * - * When the Strategy calls this the msg.sender would be the - * address of the strategy so we need to specify the sender. - * - * @param _sender The original msg.sender. - */ - function requireKeeperOrManagement(address _sender) public view { - StrategyData storage S = _strategyStorage(); - require(_sender == S.keeper || _sender == S.management, "!keeper"); - } + /// @notice Used for fee calculations. + uint256 internal constant MAX_BPS = 10_000; + /// @notice Used for profit unlocking rate calculations. + uint256 internal constant MAX_BPS_EXTENDED = 1_000_000_000_000; + /// @notice Holder for dead shares minted against unsolicited initial assets. + address internal constant DEAD_ADDRESS = + 0x000000000000000000000000000000000000dEaD; + /// @notice Supply floor below which accrued profit is minted to + /// {DEAD_ADDRESS} to block first-depositor inflation. + uint256 internal constant MINIMUM_SUPPLY = 1e3; - /** - * @notice Require a caller is the `management` or `emergencyAdmin`. - * @dev Is left public so that it can be used by the Strategy. - * - * When the Strategy calls this the msg.sender would be the - * address of the strategy so we need to specify the sender. - * - * @param _sender The original msg.sender. - */ - function requireEmergencyAuthorized(address _sender) public view { - StrategyData storage S = _strategyStorage(); - require( - _sender == S.emergencyAdmin || _sender == S.management, - "!emergency authorized" - ); - } + /** + * @dev Custom storage slot that will be used to store the + * `StrategyData` struct that holds each strategies + * specific storage variables. + * + * Any storage updates done by the TokenizedStrategy actually update + * the storage of the calling contract. This variable points + * to the specific location that will be used to store the + * struct that holds all that data. + * + * We use a custom string in order to get a random + * storage slot that will allow for strategists to use any + * amount of storage in their strategy without worrying + * about collisions. + */ + bytes32 internal constant BASE_STRATEGY_STORAGE = + bytes32(uint256(keccak256("yearn.base.strategy.storage")) - 1); + + /*////////////////////////////////////////////////////////////// + IMMUTABLE + //////////////////////////////////////////////////////////////*/ + + /// @notice Address of the previously deployed Vault factory that the + // protocol fee config is retrieved from. + address public immutable FACTORY; + + /*////////////////////////////////////////////////////////////// + STORAGE GETTER + //////////////////////////////////////////////////////////////*/ - /*////////////////////////////////////////////////////////////// - CONSTANTS - //////////////////////////////////////////////////////////////*/ - - /// @notice API version this TokenizedStrategy implements. - string internal constant API_VERSION = "3.0.3"; - - /// @notice Value to set the `entered` flag to during a call. - uint8 internal constant ENTERED = 2; - /// @notice Value to set the `entered` flag to at the end of the call. - uint8 internal constant NOT_ENTERED = 1; - - /// @notice Maximum in Basis Points the Performance Fee can be set to. - uint16 public constant MAX_FEE = 5_000; // 50% - - /// @notice Used for fee calculations. - uint256 internal constant MAX_BPS = 10_000; - /// @notice Used for profit unlocking rate calculations. - uint256 internal constant MAX_BPS_EXTENDED = 1_000_000_000_000; - - /// @notice Seconds per year for max profit unlocking time. - uint256 internal constant SECONDS_PER_YEAR = 31_556_952; // 365.2425 days - - /** - * @dev Custom storage slot that will be used to store the - * `StrategyData` struct that holds each strategies - * specific storage variables. - * - * Any storage updates done by the TokenizedStrategy actually update - * the storage of the calling contract. This variable points - * to the specific location that will be used to store the - * struct that holds all that data. - * - * We use a custom string in order to get a random - * storage slot that will allow for strategists to use any - * amount of storage in their strategy without worrying - * about collisions. - */ - bytes32 internal constant BASE_STRATEGY_STORAGE = - bytes32(uint256(keccak256("yearn.base.strategy.storage")) - 1); - - /*////////////////////////////////////////////////////////////// - IMMUTABLE - //////////////////////////////////////////////////////////////*/ - - /// @notice Address of the previously deployed Vault factory that the - // protocol fee config is retrieved from. - address public immutable FACTORY; - - /*////////////////////////////////////////////////////////////// - STORAGE GETTER - //////////////////////////////////////////////////////////////*/ - - /** - * @dev will return the actual storage slot where the strategy - * specific `StrategyData` struct is stored for both read - * and write operations. - * - * This loads just the slot location, not the full struct - * so it can be used in a gas efficient manner. - */ - function _strategyStorage() internal pure returns (StrategyData storage S) { - // Since STORAGE_SLOT is a constant, we have to put a variable - // on the stack to access it from an inline assembly block. - bytes32 slot = BASE_STRATEGY_STORAGE; - assembly { - S.slot := slot - } + /** + * @dev will return the actual storage slot where the strategy + * specific `StrategyData` struct is stored for both read + * and write operations. + * + * This loads just the slot location, not the full struct + * so it can be used in a gas efficient manner. + */ + function _strategyStorage() internal pure returns (StrategyData storage S) { + // Since STORAGE_SLOT is a constant, we have to put a variable + // on the stack to access it from an inline assembly block. + bytes32 slot = BASE_STRATEGY_STORAGE; + assembly { + S.slot := slot } + } - /*////////////////////////////////////////////////////////////// - INITIALIZATION - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Used to initialize storage for a newly deployed strategy. - * @dev This should be called atomically whenever a new strategy is - * deployed and can only be called once for each strategy. - * - * This will set all the default storage that must be set for a - * strategy to function. Any changes can be made post deployment - * through external calls from `management`. - * - * The function will also emit an event that off chain indexers can - * look for to track any new deployments using this TokenizedStrategy. - * - * @param _asset Address of the underlying asset. - * @param _name Name the strategy will use. - * @param _management Address to set as the strategies `management`. - * @param _performanceFeeRecipient Address to receive performance fees. - * @param _keeper Address to set as strategies `keeper`. - */ - function initialize( - address _asset, - string memory _name, - address _management, - address _performanceFeeRecipient, - address _keeper - ) external { - // Cache storage pointer. - StrategyData storage S = _strategyStorage(); - - // Make sure we aren't initialized. - require(address(S.asset) == address(0), "initialized"); - - // Set the strategy's underlying asset. - S.asset = ERC20(_asset); - // Set the Strategy Tokens name. - S.name = _name; - // Set decimals based off the `asset`. - S.decimals = ERC20(_asset).decimals(); - - // Default to a 10 day profit unlock period. - S.profitMaxUnlockTime = 10 days; - // Set address to receive performance fees. - // Can't be address(0) or we will be burning fees. - require(_performanceFeeRecipient != address(0), "ZERO ADDRESS"); - // Can't mint shares to its self because of profit locking. - require(_performanceFeeRecipient != address(this), "self"); - S.performanceFeeRecipient = _performanceFeeRecipient; - // Default to a 10% performance fee. - S.performanceFee = 1_000; - // Set last report to this block. - S.lastReport = uint96(block.timestamp); - - // Set the default management address. Can't be 0. - require(_management != address(0), "ZERO ADDRESS"); - S.management = _management; - // Set the keeper address - S.keeper = _keeper; - - // Emit event to signal a new strategy has been initialized. - emit NewTokenizedStrategy(address(this), _asset, API_VERSION); - } + /*////////////////////////////////////////////////////////////// + INITIALIZATION + //////////////////////////////////////////////////////////////*/ - /*////////////////////////////////////////////////////////////// - ERC4626 WRITE METHODS - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Mints `shares` of strategy shares to `receiver` by - * depositing exactly `assets` of underlying tokens. - * @param assets The amount of underlying to deposit in. - * @param receiver The address to receive the `shares`. - * @return shares The actual amount of shares issued. - */ - function deposit( - uint256 assets, - address receiver - ) external nonReentrant returns (uint256 shares) { - // Get the storage slot for all following calls. - StrategyData storage S = _strategyStorage(); - - // Deposit full balance if using max uint. - if (assets == type(uint256).max) { - assets = S.asset.balanceOf(msg.sender); - } + /** + * @notice Used to initialize storage for a newly deployed strategy. + * @dev This should be called atomically whenever a new strategy is + * deployed and can only be called once for each strategy. + * + * This will set all the default storage that must be set for a + * strategy to function. Any changes can be made post deployment + * through external calls from `management`. + * + * The function will also emit an event that off chain indexers can + * look for to track any new deployments using this TokenizedStrategy. + * + * @param _asset Address of the underlying asset. + * @param _name Name the strategy will use. + * @param _management Address to set as the strategies `management`. + * @param _performanceFeeRecipient Address to receive performance fees. + * @param _keeper Address to set as strategies `keeper`. + */ + function initialize( + address _asset, + string memory _name, + address _management, + address _performanceFeeRecipient, + address _keeper + ) external { + // Cache storage pointer. + StrategyData storage S = _strategyStorage(); + + // Make sure we aren't initialized. + require(address(S.asset) == address(0), "initialized"); + + // Set the strategy's underlying asset. + S.asset = ERC20(_asset); + // Set the Strategy Tokens name. + S.name = _name; + // Set decimals based off the `asset`. + S.decimals = ERC20(_asset).decimals(); + + // Default to a 10 day profit unlock period. + S.profitMaxUnlockTime = 10 days; + // Set address to receive performance fees. + // Can't be address(0) or we will be burning fees. + require(_performanceFeeRecipient != address(0), "ZERO ADDRESS"); + // Can't mint shares to its self because of profit locking. + require(_performanceFeeRecipient != address(this), "self"); + S.performanceFeeRecipient = _performanceFeeRecipient; + // Default to a 10% performance fee. + S.performanceFee = 1_000; + // Initialize both timestamps to the deployment block. + S.lastReport = uint96(block.timestamp); + // -1 to not allow first deposit inflation + S.lastAccrual = uint72(block.timestamp - 1); + + // Set the default management address. Can't be 0. + require(_management != address(0), "ZERO ADDRESS"); + S.management = _management; + // Set the keeper address + S.keeper = _keeper; + + // Emit event to signal a new strategy has been initialized. + emit NewTokenizedStrategy(address(this), _asset, API_VERSION); + } - // Checking max deposit will also check if shutdown. - require( - assets <= _maxDeposit(S, receiver), - "ERC4626: deposit more than max" - ); - // Check for rounding error. - require( - (shares = _convertToShares(S, assets, Math.Rounding.Down)) != 0, - "ZERO_SHARES" - ); + /*////////////////////////////////////////////////////////////// + ERC4626 WRITE METHODS + //////////////////////////////////////////////////////////////*/ - _deposit(S, receiver, assets, shares); - } + /** + * @notice Mints `shares` of strategy shares to `receiver` by + * depositing exactly `assets` of underlying tokens. + * @param assets The amount of underlying to deposit in. + * @param receiver The address to receive the `shares`. + * @return shares The actual amount of shares issued. + */ + function deposit( + uint256 assets, + address receiver + ) external whenNotPaused nonReentrant returns (uint256 shares) { + // Get the storage slot for all following calls. + StrategyData storage S = _strategyStorage(); + _accrue(S); + + // Deposit full balance if using max uint. + if (assets == type(uint256).max) { + assets = S.asset.balanceOf(msg.sender); + } + + // Checking max deposit will also check if shutdown. + require( + assets <= _maxDeposit(S, receiver), + "ERC4626: deposit more than max" + ); + // Check for rounding error. + require( + (shares = _convertToShares(S, assets, Math.Rounding.Down)) != 0, + "ZERO_SHARES" + ); - /** - * @notice Mints exactly `shares` of strategy shares to - * `receiver` by depositing `assets` of underlying tokens. - * @param shares The amount of strategy shares mint. - * @param receiver The address to receive the `shares`. - * @return assets The actual amount of asset deposited. - */ - function mint( - uint256 shares, - address receiver - ) external nonReentrant returns (uint256 assets) { - // Get the storage slot for all following calls. - StrategyData storage S = _strategyStorage(); - - // Checking max mint will also check if shutdown. - require(shares <= _maxMint(S, receiver), "ERC4626: mint more than max"); - // Check for rounding error. - require( - (assets = _convertToAssets(S, shares, Math.Rounding.Up)) != 0, - "ZERO_ASSETS" - ); + _deposit(S, receiver, assets, shares); + } - _deposit(S, receiver, assets, shares); - } + /** + * @notice Mints exactly `shares` of strategy shares to + * `receiver` by depositing `assets` of underlying tokens. + * @param shares The amount of strategy shares mint. + * @param receiver The address to receive the `shares`. + * @return assets The actual amount of asset deposited. + */ + function mint( + uint256 shares, + address receiver + ) external whenNotPaused nonReentrant returns (uint256 assets) { + // Get the storage slot for all following calls. + StrategyData storage S = _strategyStorage(); + _accrue(S); + + // Checking max mint will also check if shutdown. + require(shares <= _maxMint(S, receiver), "ERC4626: mint more than max"); + // Check for rounding error. + require( + (assets = _convertToAssets(S, shares, Math.Rounding.Up)) != 0, + "ZERO_ASSETS" + ); - /** - * @notice Withdraws exactly `assets` from `owners` shares and sends - * the underlying tokens to `receiver`. - * @dev This will default to not allowing any loss to be taken. - * @param assets The amount of underlying to withdraw. - * @param receiver The address to receive `assets`. - * @param owner The address whose shares are burnt. - * @return shares The actual amount of shares burnt. - */ - function withdraw( - uint256 assets, - address receiver, - address owner - ) external returns (uint256 shares) { - return withdraw(assets, receiver, owner, 0); - } + _deposit(S, receiver, assets, shares); + } - /** - * @notice Withdraws `assets` from `owners` shares and sends - * the underlying tokens to `receiver`. - * @dev This includes an added parameter to allow for losses. - * @param assets The amount of underlying to withdraw. - * @param receiver The address to receive `assets`. - * @param owner The address whose shares are burnt. - * @param maxLoss The amount of acceptable loss in Basis points. - * @return shares The actual amount of shares burnt. - */ - function withdraw( - uint256 assets, - address receiver, - address owner, - uint256 maxLoss - ) public nonReentrant returns (uint256 shares) { - // Get the storage slot for all following calls. - StrategyData storage S = _strategyStorage(); - require( - assets <= _maxWithdraw(S, owner), - "ERC4626: withdraw more than max" - ); - // Check for rounding error or 0 value. - require( - (shares = _convertToShares(S, assets, Math.Rounding.Up)) != 0, - "ZERO_SHARES" - ); + /** + * @notice Withdraws exactly `assets` from `owners` shares and sends + * the underlying tokens to `receiver`. + * @dev This will default to not allowing any loss to be taken. + * @param assets The amount of underlying to withdraw. + * @param receiver The address to receive `assets`. + * @param owner The address whose shares are burnt. + * @return shares The actual amount of shares burnt. + */ + function withdraw( + uint256 assets, + address receiver, + address owner + ) external returns (uint256 shares) { + return withdraw(assets, receiver, owner, 0); + } - // Withdraw and track the actual amount withdrawn for loss check. - _withdraw(S, receiver, owner, assets, shares, maxLoss); - } + /** + * @notice Withdraws `assets` from `owners` shares and sends + * the underlying tokens to `receiver`. + * @dev This includes an added parameter to allow for losses. + * @param assets The amount of underlying to withdraw. + * @param receiver The address to receive `assets`. + * @param owner The address whose shares are burnt. + * @param maxLoss The amount of acceptable loss in Basis points. + * @return shares The actual amount of shares burnt. + */ + function withdraw( + uint256 assets, + address receiver, + address owner, + uint256 maxLoss + ) public whenNotPaused nonReentrant returns (uint256 shares) { + // Get the storage slot for all following calls. + StrategyData storage S = _strategyStorage(); + _accrue(S); + + require( + assets <= _maxWithdraw(S, owner), + "ERC4626: withdraw more than max" + ); + // Check for rounding error or 0 value. + require( + (shares = _convertToShares(S, assets, Math.Rounding.Up)) != 0, + "ZERO_SHARES" + ); - /** - * @notice Redeems exactly `shares` from `owner` and - * sends `assets` of underlying tokens to `receiver`. - * @dev This will default to allowing any loss passed to be realized. - * @param shares The amount of shares burnt. - * @param receiver The address to receive `assets`. - * @param owner The address whose shares are burnt. - * @return assets The actual amount of underlying withdrawn. - */ - function redeem( - uint256 shares, - address receiver, - address owner - ) external returns (uint256) { - // We default to not limiting a potential loss. - return redeem(shares, receiver, owner, MAX_BPS); - } + // Withdraw and track the actual amount withdrawn for loss check. + _withdraw(S, receiver, owner, assets, shares, maxLoss); + } - /** - * @notice Redeems exactly `shares` from `owner` and - * sends `assets` of underlying tokens to `receiver`. - * @dev This includes an added parameter to allow for losses. - * @param shares The amount of shares burnt. - * @param receiver The address to receive `assets`. - * @param owner The address whose shares are burnt. - * @param maxLoss The amount of acceptable loss in Basis points. - * @return . The actual amount of underlying withdrawn. - */ - function redeem( - uint256 shares, - address receiver, - address owner, - uint256 maxLoss - ) public nonReentrant returns (uint256) { - // Get the storage slot for all following calls. - StrategyData storage S = _strategyStorage(); - require( - shares <= _maxRedeem(S, owner), - "ERC4626: redeem more than max" - ); - uint256 assets; - // Check for rounding error or 0 value. - require( - (assets = _convertToAssets(S, shares, Math.Rounding.Down)) != 0, - "ZERO_ASSETS" - ); + /** + * @notice Redeems exactly `shares` from `owner` and + * sends `assets` of underlying tokens to `receiver`. + * @dev This will default to allowing any loss passed to be realized. + * @param shares The amount of shares burnt. + * @param receiver The address to receive `assets`. + * @param owner The address whose shares are burnt. + * @return assets The actual amount of underlying withdrawn. + */ + function redeem( + uint256 shares, + address receiver, + address owner + ) external returns (uint256) { + // We default to not limiting a potential loss. + return redeem(shares, receiver, owner, MAX_BPS); + } - // We need to return the actual amount withdrawn in case of a loss. - return _withdraw(S, receiver, owner, assets, shares, maxLoss); - } + /** + * @notice Redeems exactly `shares` from `owner` and + * sends `assets` of underlying tokens to `receiver`. + * @dev This includes an added parameter to allow for losses. + * @param shares The amount of shares burnt. + * @param receiver The address to receive `assets`. + * @param owner The address whose shares are burnt. + * @param maxLoss The amount of acceptable loss in Basis points. + * @return . The actual amount of underlying withdrawn. + */ + function redeem( + uint256 shares, + address receiver, + address owner, + uint256 maxLoss + ) public whenNotPaused nonReentrant returns (uint256) { + // Get the storage slot for all following calls. + StrategyData storage S = _strategyStorage(); + _accrue(S); + + require( + shares <= _maxRedeem(S, owner), + "ERC4626: redeem more than max" + ); + uint256 assets; + // Check for rounding error or 0 value. + require( + (assets = _convertToAssets(S, shares, Math.Rounding.Down)) != 0, + "ZERO_ASSETS" + ); - /*////////////////////////////////////////////////////////////// - EXTERNAL 4626 VIEW METHODS - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Get the total amount of assets this strategy holds - * as of the last report. - * - * We manually track `totalAssets` to avoid any PPS manipulation. - * - * @return . Total assets the strategy holds. - */ - function totalAssets() external view returns (uint256) { - return _totalAssets(_strategyStorage()); - } + // We need to return the actual amount withdrawn in case of a loss. + return _withdraw(S, receiver, owner, assets, shares, maxLoss); + } - /** - * @notice Get the current supply of the strategies shares. - * - * Locked shares issued to the strategy from profits are not - * counted towards the full supply until they are unlocked. - * - * As more shares slowly unlock the totalSupply will decrease - * causing the PPS of the strategy to increase. - * - * @return . Total amount of shares outstanding. - */ - function totalSupply() external view returns (uint256) { - return _totalSupply(_strategyStorage()); - } + /*////////////////////////////////////////////////////////////// + EXTERNAL 4626 VIEW METHODS + //////////////////////////////////////////////////////////////*/ - /** - * @notice The amount of shares that the strategy would - * exchange for the amount of assets provided, in an - * ideal scenario where all the conditions are met. - * - * @param assets The amount of underlying. - * @return . Expected shares that `assets` represents. - */ - function convertToShares(uint256 assets) external view returns (uint256) { - return _convertToShares(_strategyStorage(), assets, Math.Rounding.Down); - } + /** + * @notice Get the total amount of assets this strategy holds + * under the current block-latched accounting estimate. + * + * Normal write flows freeze this value after the first sync in a block. + * A manual {report} can refresh it again within that same block. + * + * @dev This reflects the *simulated* constant-accrual state, including + * any pending profit or loss that has not yet been realized by a + * state-changing accrual. {convertToShares}, {convertToAssets} and all + * preview functions use the same simulated state, while {totalSupply} + * only reflects realized ERC20 supply. The two views can therefore + * appear inconsistent until the pending accrual is realized. + * + * @return . Total assets the strategy holds. + */ + function totalAssets() external view returns (uint256) { + return _totalAssets(_strategyStorage()); + } - /** - * @notice The amount of assets that the strategy would - * exchange for the amount of shares provided, in an - * ideal scenario where all the conditions are met. - * - * @param shares The amount of the strategies shares. - * @return . Expected amount of `asset` the shares represents. - */ - function convertToAssets(uint256 shares) external view returns (uint256) { - return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Down); - } + /** + * @notice Get the current supply of the strategies shares. + * + * @dev This is the *realized* ERC20 supply (stored supply minus + * unlocked strategy-held shares). It does not include fee shares + * that would be minted for pending constant-accrual profit, nor the + * locked-share burn simulated for pending losses. {totalAssets}, + * conversions and previews do reflect that simulated state, so + * comparing this value against those views may show different + * accounting assumptions until the pending accrual is realized. + * + * @return . Total amount of shares outstanding. + */ + function totalSupply() external view returns (uint256) { + return _totalSupply(_strategyStorage()); + } - /** - * @notice Allows an on-chain or off-chain user to simulate - * the effects of their deposit at the current block, given - * current on-chain conditions. - * @dev This will round down. - * - * @param assets The amount of `asset` to deposits. - * @return . Expected shares that would be issued. - */ - function previewDeposit(uint256 assets) external view returns (uint256) { - return _convertToShares(_strategyStorage(), assets, Math.Rounding.Down); - } + /** + * @notice The amount of shares that the strategy would + * exchange for the amount of assets provided, in an + * ideal scenario where all the conditions are met. + * + * @param assets The amount of underlying. + * @return . Expected shares that `assets` represents. + */ + function convertToShares(uint256 assets) external view returns (uint256) { + return _convertToShares(_strategyStorage(), assets, Math.Rounding.Down); + } - /** - * @notice Allows an on-chain or off-chain user to simulate - * the effects of their mint at the current block, given - * current on-chain conditions. - * @dev This is used instead of convertToAssets so that it can - * round up for safer mints. - * - * @param shares The amount of shares to mint. - * @return . The needed amount of `asset` for the mint. - */ - function previewMint(uint256 shares) external view returns (uint256) { - return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Up); - } + /** + * @notice The amount of assets that the strategy would + * exchange for the amount of shares provided, in an + * ideal scenario where all the conditions are met. + * + * @param shares The amount of the strategies shares. + * @return . Expected amount of `asset` the shares represents. + */ + function convertToAssets(uint256 shares) external view returns (uint256) { + return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Down); + } - /** - * @notice Allows an on-chain or off-chain user to simulate - * the effects of their withdrawal at the current block, - * given current on-chain conditions. - * @dev This is used instead of convertToShares so that it can - * round up for safer withdraws. - * - * @param assets The amount of `asset` that would be withdrawn. - * @return . The amount of shares that would be burnt. - */ - function previewWithdraw(uint256 assets) external view returns (uint256) { - return _convertToShares(_strategyStorage(), assets, Math.Rounding.Up); - } + /** + * @notice Allows an on-chain or off-chain user to simulate + * the effects of their deposit at the current block, given + * current on-chain conditions. + * @dev This will round down. + * + * @param assets The amount of `asset` to deposits. + * @return . Expected shares that would be issued. + */ + function previewDeposit(uint256 assets) external view returns (uint256) { + return _convertToShares(_strategyStorage(), assets, Math.Rounding.Down); + } - /** - * @notice Allows an on-chain or off-chain user to simulate - * the effects of their redemption at the current block, - * given current on-chain conditions. - * @dev This will round down. - * - * @param shares The amount of shares that would be redeemed. - * @return . The amount of `asset` that would be returned. - */ - function previewRedeem(uint256 shares) external view returns (uint256) { - return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Down); - } + /** + * @notice Allows an on-chain or off-chain user to simulate + * the effects of their mint at the current block, given + * current on-chain conditions. + * @dev This is used instead of convertToAssets so that it can + * round up for safer mints. + * + * @param shares The amount of shares to mint. + * @return . The needed amount of `asset` for the mint. + */ + function previewMint(uint256 shares) external view returns (uint256) { + return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Up); + } - /** - * @notice Total number of underlying assets that can - * be deposited into the strategy, where `receiver` - * corresponds to the receiver of the shares of a {deposit} call. - * - * @param receiver The address receiving the shares. - * @return . The max that `receiver` can deposit in `asset`. - */ - function maxDeposit(address receiver) external view returns (uint256) { - return _maxDeposit(_strategyStorage(), receiver); - } + /** + * @notice Allows an on-chain or off-chain user to simulate + * the effects of their withdrawal at the current block, + * given current on-chain conditions. + * @dev This is used instead of convertToShares so that it can + * round up for safer withdraws. + * + * @param assets The amount of `asset` that would be withdrawn. + * @return . The amount of shares that would be burnt. + */ + function previewWithdraw(uint256 assets) external view returns (uint256) { + return _convertToShares(_strategyStorage(), assets, Math.Rounding.Up); + } - /** - * @notice Total number of shares that can be minted to `receiver` - * of a {mint} call. - * - * @param receiver The address receiving the shares. - * @return _maxMint The max that `receiver` can mint in shares. - */ - function maxMint(address receiver) external view returns (uint256) { - return _maxMint(_strategyStorage(), receiver); - } + /** + * @notice Allows an on-chain or off-chain user to simulate + * the effects of their redemption at the current block, + * given current on-chain conditions. + * @dev This will round down. + * + * @param shares The amount of shares that would be redeemed. + * @return . The amount of `asset` that would be returned. + */ + function previewRedeem(uint256 shares) external view returns (uint256) { + return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Down); + } - /** - * @notice Total number of underlying assets that can be - * withdrawn from the strategy by `owner`, where `owner` - * corresponds to the msg.sender of a {redeem} call. - * - * @param owner The owner of the shares. - * @return _maxWithdraw Max amount of `asset` that can be withdrawn. - */ - function maxWithdraw(address owner) external view returns (uint256) { - return _maxWithdraw(_strategyStorage(), owner); - } + /** + * @notice Total number of underlying assets that can + * be deposited into the strategy, where `receiver` + * corresponds to the receiver of the shares of a {deposit} call. + * + * @param receiver The address receiving the shares. + * @return . The max that `receiver` can deposit in `asset`. + */ + function maxDeposit(address receiver) external view returns (uint256) { + return _maxDeposit(_strategyStorage(), receiver); + } - /** - * @notice Variable `maxLoss` is ignored. - * @dev Accepts a `maxLoss` variable in order to match the multi - * strategy vaults ABI. - */ - function maxWithdraw( - address owner, - uint256 /*maxLoss*/ - ) external view returns (uint256) { - return _maxWithdraw(_strategyStorage(), owner); - } + /** + * @notice Total number of shares that can be minted to `receiver` + * of a {mint} call. + * + * @param receiver The address receiving the shares. + * @return _maxMint The max that `receiver` can mint in shares. + */ + function maxMint(address receiver) external view returns (uint256) { + return _maxMint(_strategyStorage(), receiver); + } - /** - * @notice Total number of strategy shares that can be - * redeemed from the strategy by `owner`, where `owner` - * corresponds to the msg.sender of a {redeem} call. - * - * @param owner The owner of the shares. - * @return _maxRedeem Max amount of shares that can be redeemed. - */ - function maxRedeem(address owner) external view returns (uint256) { - return _maxRedeem(_strategyStorage(), owner); - } + /** + * @notice Total number of underlying assets that can be + * withdrawn from the strategy by `owner`, where `owner` + * corresponds to the msg.sender of a {redeem} call. + * + * @param owner The owner of the shares. + * @return _maxWithdraw Max amount of `asset` that can be withdrawn. + */ + function maxWithdraw(address owner) external view returns (uint256) { + return _maxWithdraw(_strategyStorage(), owner); + } - /** - * @notice Variable `maxLoss` is ignored. - * @dev Accepts a `maxLoss` variable in order to match the multi - * strategy vaults ABI. - */ - function maxRedeem( - address owner, - uint256 /*maxLoss*/ - ) external view returns (uint256) { - return _maxRedeem(_strategyStorage(), owner); - } + /** + * @notice Variable `maxLoss` is ignored. + * @dev Accepts a `maxLoss` variable in order to match the multi + * strategy vaults ABI. + */ + function maxWithdraw( + address owner, + uint256 /*maxLoss*/ + ) external view returns (uint256) { + return _maxWithdraw(_strategyStorage(), owner); + } - /*////////////////////////////////////////////////////////////// - INTERNAL 4626 VIEW METHODS - //////////////////////////////////////////////////////////////*/ + /** + * @notice Total number of strategy shares that can be + * redeemed from the strategy by `owner`, where `owner` + * corresponds to the msg.sender of a {redeem} call. + * + * @param owner The owner of the shares. + * @return _maxRedeem Max amount of shares that can be redeemed. + */ + function maxRedeem(address owner) external view returns (uint256) { + return _maxRedeem(_strategyStorage(), owner); + } - /// @dev Internal implementation of {totalAssets}. - function _totalAssets( - StrategyData storage S - ) internal view returns (uint256) { - return S.totalAssets; - } + /** + * @notice Variable `maxLoss` is ignored. + * @dev Accepts a `maxLoss` variable in order to match the multi + * strategy vaults ABI. + */ + function maxRedeem( + address owner, + uint256 /*maxLoss*/ + ) external view returns (uint256) { + return _maxRedeem(_strategyStorage(), owner); + } - /// @dev Internal implementation of {totalSupply}. - function _totalSupply( - StrategyData storage S - ) internal view returns (uint256) { - return S.totalSupply - _unlockedShares(S); - } + /*////////////////////////////////////////////////////////////// + INTERNAL 4626 VIEW METHODS + //////////////////////////////////////////////////////////////*/ - /// @dev Internal implementation of {convertToShares}. - function _convertToShares( - StrategyData storage S, - uint256 assets, - Math.Rounding _rounding - ) internal view returns (uint256) { - // Saves an extra SLOAD if values are non-zero. - uint256 totalSupply_ = _totalSupply(S); - // If supply is 0, PPS = 1. - if (totalSupply_ == 0) return assets; - - uint256 totalAssets_ = _totalAssets(S); - // If assets are 0 but supply is not PPS = 0. - if (totalAssets_ == 0) return 0; - - return assets.mulDiv(totalSupply_, totalAssets_, _rounding); - } + /// @dev Internal implementation of {totalAssets}. + function _totalAssets( + StrategyData storage S + ) internal view returns (uint256) { + (, uint256 assets) = _simulatedTotals(S); + return assets; + } - /// @dev Internal implementation of {convertToAssets}. - function _convertToAssets( - StrategyData storage S, - uint256 shares, - Math.Rounding _rounding - ) internal view returns (uint256) { - // Saves an extra SLOAD if totalSupply() is non-zero. - uint256 supply = _totalSupply(S); + /// @dev Internal implementation of {totalSupply}. + /// @notice We don't increase totalSupply until actual shares are minted. + /// This can cause disconnection between conversions done manually. + function _totalSupply( + StrategyData storage S + ) internal view returns (uint256) { + return S.totalSupply - _unlockedShares(S); + } - return - supply == 0 - ? shares - : shares.mulDiv(_totalAssets(S), supply, _rounding); + /// @dev Internal helper to simulate the supply/assets state under the current block latch. + function _simulatedTotals( + StrategyData storage S + ) internal view returns (uint256 supply, uint256 assets) { + supply = _totalSupply(S); + + if (S.entered == ENTERED || block.timestamp == S.lastAccrual) { + return (supply, S.lastTotalAssets); } - /// @dev Internal implementation of {maxDeposit}. - function _maxDeposit( - StrategyData storage S, - address receiver - ) internal view returns (uint256) { - // Cannot deposit when shutdown or to the strategy. - if (S.shutdown || receiver == address(this)) return 0; + assets = _strategyTotalAssets(); - return IBaseStrategy(address(this)).availableDepositLimit(receiver); + if ( + S.lastTotalAssets == 0 + // Mirrors {_accrue}: supply floor dead mint, fee-free recovery. + ) { + return (supply < MINIMUM_SUPPLY ? supply + assets : supply, assets); } - /// @dev Internal implementation of {maxMint}. - function _maxMint( - StrategyData storage S, - address receiver - ) internal view returns (uint256 maxMint_) { - // Cannot mint when shutdown or to the strategy. - if (S.shutdown || receiver == address(this)) return 0; - - maxMint_ = IBaseStrategy(address(this)).availableDepositLimit(receiver); - if (maxMint_ != type(uint256).max) { - maxMint_ = _convertToShares(S, maxMint_, Math.Rounding.Down); + if (assets > S.lastTotalAssets) { + uint256 profit; + unchecked { + profit = assets - S.lastTotalAssets; } - } - - /// @dev Internal implementation of {maxWithdraw}. - function _maxWithdraw( - StrategyData storage S, - address owner - ) internal view returns (uint256 maxWithdraw_) { - // Get the max the owner could withdraw currently. - maxWithdraw_ = IBaseStrategy(address(this)).availableWithdrawLimit( - owner - ); - // If there is no limit enforced. - if (maxWithdraw_ == type(uint256).max) { - // Saves a min check if there is no withdrawal limit. - maxWithdraw_ = _convertToAssets( - S, - _balanceOf(S, owner), - Math.Rounding.Down + if (supply < MINIMUM_SUPPLY) { + // Mirrors the {_accrue} supply floor confiscation. + supply += _convertToSharesFromTotals( + profit, + supply, + S.lastTotalAssets, + Math.Rounding.Up ); } else { - maxWithdraw_ = Math.min( - _convertToAssets(S, _balanceOf(S, owner), Math.Rounding.Down), - maxWithdraw_ - ); + uint16 fee = S.performanceFee; + if (fee != 0) { + uint256 totalFees = (profit * fee) / MAX_BPS; + supply += _convertToSharesFromTotals( + totalFees, + supply, + assets - totalFees, + Math.Rounding.Down + ); + } } - } - - /// @dev Internal implementation of {maxRedeem}. - function _maxRedeem( - StrategyData storage S, - address owner - ) internal view returns (uint256 maxRedeem_) { - // Get the max the owner could withdraw currently. - maxRedeem_ = IBaseStrategy(address(this)).availableWithdrawLimit(owner); - - // Conversion would overflow and saves a min check if there is no withdrawal limit. - if (maxRedeem_ == type(uint256).max) { - maxRedeem_ = _balanceOf(S, owner); - } else { - maxRedeem_ = Math.min( - // Can't redeem more than the balance. - _convertToShares(S, maxRedeem_, Math.Rounding.Down), - _balanceOf(S, owner) - ); + } else if (assets < S.lastTotalAssets) { + uint256 loss; + unchecked { + loss = S.lastTotalAssets - assets; } + + (uint256 lockedBurn, ) = _lossBurnState( + S, + loss, + supply, + S.lastTotalAssets + ); + supply -= lockedBurn; } + } + + /// @dev Internal helper to ask the strategy for its current total assets. + function _strategyTotalAssets() internal view returns (uint256) { + return IBaseStrategy(address(this)).strategyTotalAssets(); + } + + /// @dev Converts using an explicit supply/assets snapshot. + function _convertToSharesFromTotals( + uint256 assets, + uint256 supply, + uint256 totalAssets_, + Math.Rounding _rounding + ) internal pure returns (uint256) { + if (supply == 0) return assets; + if (totalAssets_ == 0) return 0; + + return assets.mulDiv(supply, totalAssets_, _rounding); + } + + /// @dev Converts using an explicit supply/assets snapshot. + function _convertToAssetsFromTotals( + uint256 shares, + uint256 supply, + uint256 totalAssets_, + Math.Rounding _rounding + ) internal pure returns (uint256) { + return + supply == 0 + ? shares + : shares.mulDiv(totalAssets_, supply, _rounding); + } - /*////////////////////////////////////////////////////////////// - INTERNAL 4626 WRITE METHODS - //////////////////////////////////////////////////////////////*/ - - /** - * @dev Function to be called during {deposit} and {mint}. - * - * This function handles all logic including transfers, - * minting and accounting. - * - * We do all external calls before updating any internal - * values to prevent view reentrancy issues from the token - * transfers or the _deployFunds() calls. - */ - function _deposit( - StrategyData storage S, - address receiver, - uint256 assets, - uint256 shares - ) internal { - // Cache storage variables used more than once. - ERC20 _asset = S.asset; - - // Need to transfer before minting or ERC777s could reenter. - _asset.safeTransferFrom(msg.sender, address(this), assets); - - // We can deploy the full loose balance currently held. - IBaseStrategy(address(this)).deployFunds( - _asset.balanceOf(address(this)) + /// @dev Internal implementation of {convertToShares}. + function _convertToShares( + StrategyData storage S, + uint256 assets, + Math.Rounding _rounding + ) internal view returns (uint256) { + (uint256 totalSupply_, uint256 totalAssets_) = _simulatedTotals(S); + // If supply is 0, PPS = 1. + return + _convertToSharesFromTotals( + assets, + totalSupply_, + totalAssets_, + _rounding ); + } - // Adjust total Assets. - S.totalAssets += assets; + /// @dev Internal implementation of {convertToAssets}. + function _convertToAssets( + StrategyData storage S, + uint256 shares, + Math.Rounding _rounding + ) internal view returns (uint256) { + (uint256 supply, uint256 totalAssets_) = _simulatedTotals(S); - // mint shares - _mint(S, receiver, shares); + return + _convertToAssetsFromTotals(shares, supply, totalAssets_, _rounding); + } + + /// @dev Internal implementation of {maxDeposit}. + function _maxDeposit( + StrategyData storage S, + address receiver + ) internal view returns (uint256) { + // Cannot deposit when shutdown, paused or to the strategy. + if (S.shutdown || S.paused || receiver == address(this)) return 0; + + return IBaseStrategy(address(this)).availableDepositLimit(receiver); + } + + /// @dev Internal implementation of {maxMint}. + function _maxMint( + StrategyData storage S, + address receiver + ) internal view returns (uint256 maxMint_) { + // Cannot mint when shutdown, paused or to the strategy. + if (S.shutdown || S.paused || receiver == address(this)) return 0; + + maxMint_ = IBaseStrategy(address(this)).availableDepositLimit(receiver); + if (maxMint_ != type(uint256).max) { + maxMint_ = _convertToShares(S, maxMint_, Math.Rounding.Down); + } + } - emit Deposit(msg.sender, receiver, assets, shares); + /// @dev Internal implementation of {maxWithdraw}. + function _maxWithdraw( + StrategyData storage S, + address owner + ) internal view returns (uint256 maxWithdraw_) { + // Cannot withdraw when paused. + if (S.paused) return 0; + + // Get the max the owner could withdraw currently. + maxWithdraw_ = IBaseStrategy(address(this)).availableWithdrawLimit( + owner + ); + + // If there is no limit enforced. + if (maxWithdraw_ == type(uint256).max) { + // Saves a min check if there is no withdrawal limit. + maxWithdraw_ = _convertToAssets( + S, + _balanceOf(S, owner), + Math.Rounding.Down + ); + } else { + maxWithdraw_ = Math.min( + _convertToAssets(S, _balanceOf(S, owner), Math.Rounding.Down), + maxWithdraw_ + ); } + } - /** - * @dev To be called during {redeem} and {withdraw}. - * - * This will handle all logic, transfers and accounting - * in order to service the withdraw request. - * - * If we are not able to withdraw the full amount needed, it will - * be counted as a loss and passed on to the user. - */ - function _withdraw( - StrategyData storage S, - address receiver, - address owner, - uint256 assets, - uint256 shares, - uint256 maxLoss - ) internal returns (uint256) { - require(receiver != address(0), "ZERO ADDRESS"); - require(maxLoss <= MAX_BPS, "exceeds MAX_BPS"); - - // Spend allowance if applicable. - if (msg.sender != owner) { - _spendAllowance(S, owner, msg.sender, shares); + /// @dev Internal implementation of {maxRedeem}. + function _maxRedeem( + StrategyData storage S, + address owner + ) internal view returns (uint256 maxRedeem_) { + // Cannot redeem when paused. + if (S.paused) return 0; + + // Get the max the owner could withdraw currently. + maxRedeem_ = IBaseStrategy(address(this)).availableWithdrawLimit(owner); + + // Conversion would overflow and saves a min check if there is no withdrawal limit. + if (maxRedeem_ == type(uint256).max) { + maxRedeem_ = _balanceOf(S, owner); + } else { + maxRedeem_ = Math.min( + // Can't redeem more than the balance. + _convertToShares(S, maxRedeem_, Math.Rounding.Down), + _balanceOf(S, owner) + ); + } + } + + /*////////////////////////////////////////////////////////////// + INTERNAL 4626 WRITE METHODS + //////////////////////////////////////////////////////////////*/ + + /** + * @dev Function to be called during {deposit} and {mint}. + * + * This function handles all logic including transfers, + * minting and accounting. + * + * We do all external calls before updating any internal + * values to prevent view reentrancy issues from the token + * transfers or the _deployFunds() calls. + */ + function _deposit( + StrategyData storage S, + address receiver, + uint256 assets, + uint256 shares + ) internal { + // Cache storage variables used more than once. + ERC20 _asset = S.asset; + + // Need to transfer before minting or ERC777s could reenter. + _asset.safeTransferFrom(msg.sender, address(this), assets); + + // We can deploy the full loose balance currently held. + IBaseStrategy(address(this)).deployFunds( + _asset.balanceOf(address(this)) + ); + + // Adjust total Assets. + S.lastTotalAssets += assets; + + // mint shares + _mint(S, receiver, shares); + + emit Deposit(msg.sender, receiver, assets, shares); + } + + /** + * @dev To be called during {redeem} and {withdraw}. + * + * This will handle all logic, transfers and accounting + * in order to service the withdraw request. + * + * If we are not able to withdraw the full amount needed, it will + * be counted as a loss and passed on to the user. + */ + function _withdraw( + StrategyData storage S, + address receiver, + address owner, + uint256 assets, + uint256 shares, + uint256 maxLoss + ) internal returns (uint256) { + require(receiver != address(0), "ZERO ADDRESS"); + require(maxLoss <= MAX_BPS, "exceeds MAX_BPS"); + + // Spend allowance if applicable. + if (msg.sender != owner) { + _spendAllowance(S, owner, msg.sender, shares); + } + + // Cache `asset` since it is used multiple times.. + ERC20 _asset = S.asset; + + uint256 idle = _asset.balanceOf(address(this)); + uint256 loss; + // Check if we need to withdraw funds. + if (idle < assets) { + // Tell Strategy to free what we need. + unchecked { + IBaseStrategy(address(this)).freeFunds(assets - idle); } - // Cache `asset` since it is used multiple times.. - ERC20 _asset = S.asset; + // Return the actual amount withdrawn. Adjust for potential under withdraws. + idle = _asset.balanceOf(address(this)); - uint256 idle = _asset.balanceOf(address(this)); - uint256 loss; - // Check if we need to withdraw funds. + // If we didn't get enough out then we have a loss. if (idle < assets) { - // Tell Strategy to free what we need. unchecked { - IBaseStrategy(address(this)).freeFunds(assets - idle); + loss = assets - idle; } - - // Return the actual amount withdrawn. Adjust for potential under withdraws. - idle = _asset.balanceOf(address(this)); - - // If we didn't get enough out then we have a loss. - if (idle < assets) { - unchecked { - loss = assets - idle; - } - // If a non-default max loss parameter was set. - if (maxLoss < MAX_BPS) { - // Make sure we are within the acceptable range. - require( - loss <= (assets * maxLoss) / MAX_BPS, - "too much loss" - ); - } - // Lower the amount to be withdrawn. - assets = idle; + // If a non-default max loss parameter was set. + if (maxLoss < MAX_BPS) { + // Make sure we are within the acceptable range. + require( + loss <= (assets * maxLoss) / MAX_BPS, + "too much loss" + ); } + // Lower the amount to be withdrawn. + assets = idle; } + } - // Update assets based on how much we took. - S.totalAssets -= (assets + loss); + // Update assets based on how much we took. + S.lastTotalAssets -= (assets + loss); - _burn(S, owner, shares); + _burn(S, owner, shares); - // Transfer the amount of underlying to the receiver. - _asset.safeTransfer(receiver, assets); + // Transfer the amount of underlying to the receiver. + _asset.safeTransfer(receiver, assets); - emit Withdraw(msg.sender, receiver, owner, assets, shares); + emit Withdraw(msg.sender, receiver, owner, assets, shares); - // Return the actual amount of assets withdrawn. - return assets; - } + // Return the actual amount of assets withdrawn. + return assets; + } - /*////////////////////////////////////////////////////////////// - PROFIT REPORTING - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Function for keepers to call to harvest and record all - * profits accrued. - * - * @dev This will account for any gains/losses since the last report - * and charge fees accordingly. - * - * Any profit over the fees charged will be immediately locked - * so there is no change in PricePerShare. Then slowly unlocked - * over the `maxProfitUnlockTime` each second based on the - * calculated `profitUnlockingRate`. - * - * In case of a loss it will first attempt to offset the loss - * with any remaining locked shares from the last report in - * order to reduce any negative impact to PPS. - * - * Will then recalculate the new time to unlock profits over and the - * rate based on a weighted average of any remaining time from the - * last report and the new amount of shares to be locked. - * - * @return profit The notional amount of gain if any since the last - * report in terms of `asset`. - * @return loss The notional amount of loss if any since the last - * report in terms of `asset`. - */ - function report() - external - nonReentrant - onlyKeepers - returns (uint256 profit, uint256 loss) - { - // Cache storage pointer since its used repeatedly. - StrategyData storage S = _strategyStorage(); - - // Tell the strategy to report the real total assets it has. - // It should do all reward selling and redepositing now and - // account for deployed and loose `asset` so we can accurately - // account for all funds including those potentially airdropped - // and then have any profits immediately locked. - uint256 newTotalAssets = IBaseStrategy(address(this)) - .harvestAndReport(); - - uint256 oldTotalAssets = _totalAssets(S); - - // Get the amount of shares we need to burn from previous reports. - uint256 sharesToBurn = _unlockedShares(S); - - // Initialize variables needed throughout. - uint256 totalFees; - uint256 protocolFees; - uint256 sharesToLock; - uint256 _profitMaxUnlockTime = S.profitMaxUnlockTime; - // Calculate profit/loss. - if (newTotalAssets > oldTotalAssets) { - // We have a profit. - unchecked { - profit = newTotalAssets - oldTotalAssets; - } + /// @dev Synchronize accounting using the strategy's current view estimate unless this block is already latched. + function _accrue( + StrategyData storage S + ) internal returns (uint256 profit, uint256 loss) { + if (block.timestamp == S.lastAccrual) { + return (0, 0); + } - // We need to get the equivalent amount of shares - // at the current PPS before any minting or burning. - sharesToLock = _convertToShares(S, profit, Math.Rounding.Down); + uint256 newTotalAssets = _strategyTotalAssets(); + uint256 oldTotalAssets = S.lastTotalAssets; + uint256 totalFees; + uint256 protocolFees; - // Cache the performance fee. - uint16 fee = S.performanceFee; - uint256 totalFeeShares; - // If we are charging a performance fee - if (fee != 0) { - // Asses performance fees. - unchecked { - // Get in `asset` for the event. - totalFees = (profit * fee) / MAX_BPS; - // And in shares for the payment. - totalFeeShares = (sharesToLock * fee) / MAX_BPS; - } + if (newTotalAssets > oldTotalAssets) { + unchecked { + profit = newTotalAssets - oldTotalAssets; + } - // Get the protocol fee config from the factory. - ( - uint16 protocolFeeBps, - address protocolFeesRecipient - ) = IFactory(FACTORY).protocol_fee_config(); - - uint256 protocolFeeShares; - // Check if there is a protocol fee to charge. - if (protocolFeeBps != 0) { - unchecked { - // Calculate protocol fees based on the performance Fees. - protocolFeeShares = - (totalFeeShares * protocolFeeBps) / - MAX_BPS; - // Need amount in underlying for event. - protocolFees = (totalFees * protocolFeeBps) / MAX_BPS; - } - - // Mint the protocol fees to the recipient. - _mint(S, protocolFeesRecipient, protocolFeeShares); - } + // Profit accrued below the supply floor is confiscated to dead + // shares at a flat PPS, fee free, so a dust supply can never + // capture a donation. + uint256 supply = _totalSupply(S); + if (supply < MINIMUM_SUPPLY) { + _mint( + S, + DEAD_ADDRESS, + // If there is no prior PPS to preserve, target 1:1. + oldTotalAssets == 0 + ? newTotalAssets + : _convertToSharesFromTotals( + profit, + supply, + oldTotalAssets, + Math.Rounding.Up + ) + ); + } else if (oldTotalAssets != 0) { + (totalFees, protocolFees, ) = _chargeFees( + S, + profit, + newTotalAssets, + true + ); + } + } else if (oldTotalAssets > newTotalAssets) { + unchecked { + loss = oldTotalAssets - newTotalAssets; + } + _realizeLoss(S, loss); + _syncUnlockScheduleAfterLoss(S); + } - // Mint the difference to the strategy fee recipient. - unchecked { - _mint( - S, - S.performanceFeeRecipient, - totalFeeShares - protocolFeeShares - ); - } - } + S.lastTotalAssets = newTotalAssets; + S.lastAccrual = uint72(block.timestamp); - // Check if we are locking profit. - if (_profitMaxUnlockTime != 0) { - // lock (profit - fees) - unchecked { - sharesToLock -= totalFeeShares; - } + emit Accrued(profit, loss, protocolFees, totalFees - protocolFees); + } - // If we are burning more than re-locking. - if (sharesToBurn > sharesToLock) { - // Burn the difference - unchecked { - _burn(S, address(this), sharesToBurn - sharesToLock); - } - } else if (sharesToLock > sharesToBurn) { - // Mint the shares to lock the strategy. - unchecked { - _mint(S, address(this), sharesToLock - sharesToBurn); - } - } - } - } else { - // Expect we have a loss. - unchecked { - loss = oldTotalAssets - newTotalAssets; - } + /// @dev Mint fee shares for asset-based live accrual. + function _chargeFees( + StrategyData storage S, + uint256 profit, + uint256 newTotalAssets, + bool useNewPps + ) + internal + returns ( + uint256 totalFees, + uint256 protocolFees, + uint256 totalFeeShares + ) + { + uint16 fee = S.performanceFee; + if (fee == 0 || S.totalSupply == 0) return (0, 0, 0); + + // Asses performance fees. + unchecked { + // Get in `asset` for the event. + totalFees = (profit * fee) / MAX_BPS; + } + + // Get fee shares based on PPS that the txn will end on. + // During live accrual or when profit unlock is 0, + // we use the new diluted PPS. During locked-profit + // reports we need to use the old PPS since it does not change. + totalFeeShares = _convertToSharesFromTotals( + totalFees, + _totalSupply(S), + useNewPps ? newTotalAssets - totalFees : S.lastTotalAssets, + Math.Rounding.Down + ); - // Check in case `else` was due to being equal. - if (loss != 0) { - // We will try and burn the unlocked shares and as much from any - // pending profit still unlocking to offset the loss to prevent any PPS decline post report. - sharesToBurn = Math.min( - // Cannot burn more than we have. - S.balances[address(this)], - // Try and burn both the shares already unlocked and the amount for the loss. - _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn - ); - } + (uint16 protocolFeeBps, address protocolFeesRecipient) = IFactory( + FACTORY + ).protocol_fee_config(); - // Check if there is anything to burn. - if (sharesToBurn != 0) { - _burn(S, address(this), sharesToBurn); - } + uint256 protocolFeeShares; + // Check if there is a protocol fee to charge. + if (protocolFeeBps != 0) { + unchecked { + // Calculate protocol fees based on the performance Fees. + protocolFeeShares = (totalFeeShares * protocolFeeBps) / MAX_BPS; + // Need amount in underlying for event. + protocolFees = (totalFees * protocolFeeBps) / MAX_BPS; } - // Update unlocking rate and time to fully unlocked. - uint256 totalLockedShares = S.balances[address(this)]; - if (totalLockedShares != 0) { - uint256 previouslyLockedTime; - uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; - // Check if we need to account for shares still unlocking. - if (_fullProfitUnlockDate > block.timestamp) { - unchecked { - // There will only be previously locked shares if time remains. - // We calculate this here since it should be rare. - previouslyLockedTime = - (_fullProfitUnlockDate - block.timestamp) * - (totalLockedShares - sharesToLock); - } - } + // Mint the protocol fees to the recipient. + _mint(S, protocolFeesRecipient, protocolFeeShares); + } + + // Mint the difference to the strategy fee recipient. + unchecked { + _mint( + S, + S.performanceFeeRecipient, + totalFeeShares - protocolFeeShares + ); + } + } + + function _realizeLoss(StrategyData storage S, uint256 loss) internal { + (, uint256 sharesToBurn) = _lossBurnState( + S, + loss, + _totalSupply(S), + S.lastTotalAssets + ); + + // Check if there is anything to burn. + if (sharesToBurn != 0) { + _burn(S, address(this), sharesToBurn); + } + } - // newProfitLockingPeriod is a weighted average between the remaining - // time of the previously locked shares and the profitMaxUnlockTime. - uint256 newProfitLockingPeriod = (previouslyLockedTime + - sharesToLock * - _profitMaxUnlockTime) / totalLockedShares; + /// @dev Returns the loss burn split between already-unlocked and still-locked shares. + function _lossBurnState( + StrategyData storage S, + uint256 loss, + uint256 supply, + uint256 totalAssets_ + ) internal view returns (uint256 lockedBurn, uint256 totalBurn) { + uint256 buffer = S.balances[address(this)]; + if (buffer == 0) return (0, 0); + + uint256 unlocked = _unlockedShares(S); + if (unlocked >= buffer) return (0, buffer); + + uint256 lossShares = _convertToSharesFromTotals( + loss, + supply, + totalAssets_, + Math.Rounding.Down + ); + + unchecked { + lockedBurn = Math.min(buffer - unlocked, lossShares); + totalBurn = unlocked + lockedBurn; + } + } - // Calculate how many shares unlock per second. + /// @dev Re-seeds unlock accounting after `_accrue` burns buffer shares for a loss. + function _syncUnlockScheduleAfterLoss(StrategyData storage S) internal { + uint256 totalLockedShares = S.balances[address(this)]; + S.lastReport = uint96(block.timestamp); + uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; + + if (_fullProfitUnlockDate > block.timestamp && totalLockedShares != 0) { + unchecked { S.profitUnlockingRate = (totalLockedShares * MAX_BPS_EXTENDED) / - newProfitLockingPeriod; + (_fullProfitUnlockDate - block.timestamp); + } + } else { + S.profitUnlockingRate = 0; + } + } - // Calculate how long until the full amount of shares is unlocked. - S.fullProfitUnlockDate = uint96( - block.timestamp + newProfitLockingPeriod - ); - } else { - // Only setting this to 0 will turn in the desired effect, - // no need to update profitUnlockingRate. - S.fullProfitUnlockDate = 0; + /*////////////////////////////////////////////////////////////// + PROFIT REPORTING + //////////////////////////////////////////////////////////////*/ + + /** + * @notice Function for keepers to call to harvest and record all + * profits accrued. + * + * @dev This will account for any gains/losses since the last report + * and charge fees accordingly. + * + * Any profit over the fees charged will be immediately locked + * so there is no change in PricePerShare. Then slowly unlocked + * over the `maxProfitUnlockTime` each second based on the + * calculated `profitUnlockingRate`. + * + * In case of a loss it will first attempt to offset the loss + * with any remaining locked shares from the last report in + * order to reduce any negative impact to PPS. + * + * Will then recalculate the new time to unlock profits over and the + * rate based on a weighted average of any remaining time from the + * last report and the new amount of shares to be locked. + * + * @return profit The notional amount of gain if any since the last + * report in terms of `asset`. + * @return loss The notional amount of loss if any since the last + * report in terms of `asset`. + */ + function report() + external + nonReentrant + onlyKeepers + returns (uint256 profit, uint256 loss) + { + // Cache storage pointer since its used repeatedly. + StrategyData storage S = _strategyStorage(); + + // Accrue to update total assets for non harvestable yield + _accrue(S); + + // Tell the strategy to report the real total assets it has. + // It should do all reward selling and redepositing now and + // account for deployed and loose `asset` so we can accurately + // account for all funds including those potentially airdropped + // and then have any profits immediately locked. + uint256 newTotalAssets = IBaseStrategy(address(this)) + .harvestAndReport(); + + uint256 oldTotalAssets = S.lastTotalAssets; + + // Initialize variables needed throughout. + uint256 totalFees; + uint256 protocolFees; + uint256 sharesToLock; + uint256 _profitMaxUnlockTime = S.profitMaxUnlockTime; + // Calculate profit/loss. + if (newTotalAssets > oldTotalAssets) { + // We have a profit. + unchecked { + profit = newTotalAssets - oldTotalAssets; } - // Update the new total assets value. - S.totalAssets = newTotalAssets; - S.lastReport = uint96(block.timestamp); + // We need to get the equivalent amount of shares + // at the current PPS before any minting or burning. + sharesToLock = _convertToShares(S, profit, Math.Rounding.Down); - // Emit event with info - emit Reported( + uint256 totalFeeShares; + (totalFees, protocolFees, totalFeeShares) = _chargeFees( + S, profit, - loss, - protocolFees, // Protocol fees - totalFees - protocolFees // Performance Fees + newTotalAssets, + _profitMaxUnlockTime == 0 ); - } - /** - * @notice Get how many shares have been unlocked since last report. - * @return . The amount of shares that have unlocked. - */ - function unlockedShares() external view returns (uint256) { - return _unlockedShares(_strategyStorage()); + // Check if we are locking profit. + if (_profitMaxUnlockTime != 0) { + // lock (profit - fees) + unchecked { + sharesToLock -= totalFeeShares; + } + + uint256 sharesToBurn = _unlockedShares(S); + // If we are burning more than re-locking. + if (sharesToBurn > sharesToLock) { + // Burn the difference + unchecked { + _burn(S, address(this), sharesToBurn - sharesToLock); + } + } else if (sharesToLock > sharesToBurn) { + // Mint the shares to lock the strategy. + unchecked { + _mint(S, address(this), sharesToLock - sharesToBurn); + } + } + } + } else { + // Expect we have a loss. + unchecked { + loss = oldTotalAssets - newTotalAssets; + } + _realizeLoss(S, loss); } - /** - * @dev To determine how many of the shares that were locked during the last - * report have since unlocked. - * - * If the `fullProfitUnlockDate` has passed the full strategy's balance will - * count as unlocked. - * - * @return unlocked The amount of shares that have unlocked. - */ - function _unlockedShares( - StrategyData storage S - ) internal view returns (uint256 unlocked) { + // Update unlocking rate and time to fully unlocked. + uint256 totalLockedShares = S.balances[address(this)]; + if (totalLockedShares != 0) { + uint256 previouslyLockedTime; uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; + // Check if we need to account for shares still unlocking. if (_fullProfitUnlockDate > block.timestamp) { unchecked { - unlocked = - (S.profitUnlockingRate * (block.timestamp - S.lastReport)) / - MAX_BPS_EXTENDED; + // There will only be previously locked shares if time remains. + // We calculate this here since it should be rare. + previouslyLockedTime = + (_fullProfitUnlockDate - block.timestamp) * + (totalLockedShares - sharesToLock); } - } else if (_fullProfitUnlockDate != 0) { - // All shares have been unlocked. - unlocked = S.balances[address(this)]; } - } - /*////////////////////////////////////////////////////////////// - TENDING - //////////////////////////////////////////////////////////////*/ - - /** - * @notice For a 'keeper' to 'tend' the strategy if a custom - * tendTrigger() is implemented. - * - * @dev Both 'tendTrigger' and '_tend' will need to be overridden - * for this to be used. - * - * This will callback the internal '_tend' call in the BaseStrategy - * with the total current amount available to the strategy to deploy. - * - * This is a permissioned function so if desired it could - * be used for illiquid or manipulatable strategies to compound - * rewards, perform maintenance or deposit/withdraw funds. - * - * This will not cause any change in PPS. Total assets will - * be the same before and after. - * - * A report() call will be needed to record any profits or losses. - */ - function tend() external nonReentrant onlyKeepers { - // Tend the strategy with the current loose balance. - IBaseStrategy(address(this)).tendThis( - _strategyStorage().asset.balanceOf(address(this)) + // newProfitLockingPeriod is a weighted average between the remaining + // time of the previously locked shares and the profitMaxUnlockTime. + uint256 newProfitLockingPeriod = (previouslyLockedTime + + sharesToLock * + _profitMaxUnlockTime) / totalLockedShares; + + // Calculate how many shares unlock per second. + S.profitUnlockingRate = + (totalLockedShares * MAX_BPS_EXTENDED) / + newProfitLockingPeriod; + + // Calculate how long until the full amount of shares is unlocked. + S.fullProfitUnlockDate = uint96( + block.timestamp + newProfitLockingPeriod ); - } + } else { + // Only setting this to 0 will turn in the desired effect, + // no need to update profitUnlockingRate. + S.fullProfitUnlockDate = 0; + } + + // Update the new total assets value. + S.lastTotalAssets = newTotalAssets; + S.lastReport = uint96(block.timestamp); + + // Emit event with info + emit Reported( + profit, + loss, + protocolFees, // Protocol fees + totalFees - protocolFees // Performance Fees + ); + } - /*////////////////////////////////////////////////////////////// - STRATEGY SHUTDOWN - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Used to shutdown the strategy preventing any further deposits. - * @dev Can only be called by the current `management` or `emergencyAdmin`. - * - * This will stop any new {deposit} or {mint} calls but will - * not prevent {withdraw} or {redeem}. It will also still allow for - * {tend} and {report} so that management can report any last losses - * in an emergency as well as provide any maintenance to allow for full - * withdraw. - * - * This is a one way switch and can never be set back once shutdown. - */ - function shutdownStrategy() external onlyEmergencyAuthorized { - _strategyStorage().shutdown = true; - - emit StrategyShutdown(); - } + /** + * @notice Get how many report-locked shares have unlocked. + * @return . The amount of shares that have unlocked. + */ + function unlockedShares() external view returns (uint256) { + return _unlockedShares(_strategyStorage()); + } - /** - * @notice To manually withdraw funds from the yield source after a - * strategy has been shutdown. - * @dev This can only be called post {shutdownStrategy}. - * - * This will never cause a change in PPS. Total assets will - * be the same before and after. - * - * A strategist will need to override the {_emergencyWithdraw} function - * in their strategy for this to work. - * - * @param amount The amount of asset to attempt to free. - */ - function emergencyWithdraw( - uint256 amount - ) external nonReentrant onlyEmergencyAuthorized { - // Make sure the strategy has been shutdown. - require(_strategyStorage().shutdown, "not shutdown"); - - // Withdraw from the yield source. - IBaseStrategy(address(this)).shutdownWithdraw(amount); + /// @dev To determine how many report-locked shares have unlocked. + function _unlockedShares( + StrategyData storage S + ) internal view returns (uint256 unlocked) { + uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate; + if (_fullProfitUnlockDate > block.timestamp) { + unchecked { + unlocked = + (S.profitUnlockingRate * (block.timestamp - S.lastReport)) / + MAX_BPS_EXTENDED; + } + } else if (_fullProfitUnlockDate != 0) { + unlocked = S.balances[address(this)]; } + } - /*////////////////////////////////////////////////////////////// - GETTER FUNCTIONS - //////////////////////////////////////////////////////////////*/ + /*////////////////////////////////////////////////////////////// + TENDING + //////////////////////////////////////////////////////////////*/ - /** - * @notice Get the underlying asset for the strategy. - * @return . The underlying asset. - */ - function asset() external view returns (address) { - return address(_strategyStorage().asset); - } + /** + * @notice For a 'keeper' to 'tend' the strategy if a custom + * tendTrigger() is implemented. + * + * @dev Both 'tendTrigger' and '_tend' will need to be overridden + * for this to be used. + * + * This will callback the internal '_tend' call in the BaseStrategy + * with the total current amount available to the strategy to deploy. + * + * This is a permissioned function so if desired it could + * be used for illiquid or manipulatable strategies to compound + * rewards, perform maintenance or deposit/withdraw funds. + * + * This performs no accounting checkpoint itself. Under constant + * accrual, any value change made by '_tend' is reflected in + * {totalAssets}, conversions and previews through simulation — + * immediately within this block if no accrual has latched it yet + * (see {totalAssets}), otherwise from the next block — and is + * realized (fees charged, losses offset) by the next state-changing + * accrual: any deposit, mint, withdraw, redeem, fee configuration + * change, or report. + * + * Any pre-existing pending profit or loss nets against the effects + * of the tend before fees are assessed. This is intended: performance + * fees are charged on the net result, not the gross. + */ + function tend() external nonReentrant onlyKeepers { + // Tend the strategy with the current loose balance. + IBaseStrategy(address(this)).tendThis( + _strategyStorage().asset.balanceOf(address(this)) + ); + } - /** - * @notice Get the API version for this TokenizedStrategy. - * @return . The API version for this TokenizedStrategy - */ - function apiVersion() external pure returns (string memory) { - return API_VERSION; - } + /*////////////////////////////////////////////////////////////// + STRATEGY SHUTDOWN + //////////////////////////////////////////////////////////////*/ - /** - * @notice Get the current address that controls the strategy. - * @return . Address of management - */ - function management() external view returns (address) { - return _strategyStorage().management; - } + /** + * @notice Used to shutdown the strategy preventing any further deposits. + * @dev Can only be called by the current `management` or `emergencyAdmin`. + * + * This will stop any new {deposit} or {mint} calls but will + * not prevent {withdraw} or {redeem}. It will also still allow for + * {tend} and {report} so that management can report any last losses + * in an emergency as well as provide any maintenance to allow for full + * withdraw. + * + * This is a one way switch and can never be set back once shutdown. + */ + function shutdownStrategy() external onlyEmergencyAuthorized { + _strategyStorage().shutdown = true; + + emit StrategyShutdown(); + } - /** - * @notice Get the current pending management address if any. - * @return . Address of pendingManagement - */ - function pendingManagement() external view returns (address) { - return _strategyStorage().pendingManagement; + /** + * @notice Used to set the pause status for user facing 4626 functions. + * @dev Pausing can be called by the current `management` or `emergencyAdmin`. + * Unpausing can only be called by the current `management`. + * + * This will stop {deposit}, {mint}, {withdraw} and {redeem}, but will + * leave management functions live so the strategy can still be tended, + * reported, configured, shutdown or manually withdrawn in an emergency. + */ + function setPaused(bool paused) external { + if (paused) { + requireEmergencyAuthorized(msg.sender); + } else { + requireManagement(msg.sender); } + _strategyStorage().paused = paused; - /** - * @notice Get the current address that can call tend and report. - * @return . Address of the keeper - */ - function keeper() external view returns (address) { - return _strategyStorage().keeper; - } + emit UpdatePaused(paused); + } - /** - * @notice Get the current address that can shutdown and emergency withdraw. - * @return . Address of the emergencyAdmin - */ - function emergencyAdmin() external view returns (address) { - return _strategyStorage().emergencyAdmin; - } + /** + * @notice To manually withdraw funds from the yield source after a + * strategy has been shutdown. + * @dev This can only be called when the strategy is paused or shutdown. + * + * This path deliberately performs no accrual so that the rescue flow + * has no dependency on `strategyTotalAssets()`, which may revert or + * be unreliable mid-emergency. Any profit or loss caused by the + * unwind follows the same rules as {tend}: it is reflected in + * {totalAssets}, conversions and previews through simulation and is + * realized by the next state-changing accrual. Management can call + * {report} afterward if controlled realization is desired. + * + * A strategist will need to override the {_emergencyWithdraw} function + * in their strategy for this to work. + * + * @param amount The amount of asset to attempt to free. + */ + function emergencyWithdraw( + uint256 amount + ) external nonReentrant onlyEmergencyAuthorized { + StrategyData storage S = _strategyStorage(); + + // Make sure the strategy has been paused or shutdown. + require(S.paused || S.shutdown, "not paused or shutdown"); + + // Withdraw from the yield source. + IBaseStrategy(address(this)).shutdownWithdraw(amount); + } - /** - * @notice Get the current performance fee charged on profits. - * denominated in Basis Points where 10_000 == 100% - * @return . Current performance fee. - */ - function performanceFee() external view returns (uint16) { - return _strategyStorage().performanceFee; - } + /*////////////////////////////////////////////////////////////// + GETTER FUNCTIONS + //////////////////////////////////////////////////////////////*/ - /** - * @notice Get the current address that receives the performance fees. - * @return . Address of performanceFeeRecipient - */ - function performanceFeeRecipient() external view returns (address) { - return _strategyStorage().performanceFeeRecipient; - } + /** + * @notice Get the underlying asset for the strategy. + * @return . The underlying asset. + */ + function asset() external view returns (address) { + return address(_strategyStorage().asset); + } - /** - * @notice Gets the timestamp at which all profits will be unlocked. - * @return . The full profit unlocking timestamp - */ - function fullProfitUnlockDate() external view returns (uint256) { - return uint256(_strategyStorage().fullProfitUnlockDate); - } + /** + * @notice Get the API version for this TokenizedStrategy. + * @return . The API version for this TokenizedStrategy + */ + function apiVersion() external pure returns (string memory) { + return API_VERSION; + } - /** - * @notice The per second rate at which profits are unlocking. - * @dev This is denominated in EXTENDED_BPS decimals. - * @return . The current profit unlocking rate. - */ - function profitUnlockingRate() external view returns (uint256) { - return _strategyStorage().profitUnlockingRate; - } + /** + * @notice Get the current address that controls the strategy. + * @return . Address of management + */ + function management() external view returns (address) { + return _strategyStorage().management; + } - /** - * @notice Gets the current time profits are set to unlock over. - * @return . The current profit max unlock time. - */ - function profitMaxUnlockTime() external view returns (uint256) { - return _strategyStorage().profitMaxUnlockTime; - } + /** + * @notice Get the current pending management address if any. + * @return . Address of pendingManagement + */ + function pendingManagement() external view returns (address) { + return _strategyStorage().pendingManagement; + } - /** - * @notice The timestamp of the last time protocol fees were charged. - * @return . The last report. - */ - function lastReport() external view returns (uint256) { - return uint256(_strategyStorage().lastReport); - } + /** + * @notice Get the current address that can call tend and report. + * @return . Address of the keeper + */ + function keeper() external view returns (address) { + return _strategyStorage().keeper; + } - /** - * @notice Get the price per share. - * @dev This value offers limited precision. Integrations that require - * exact precision should use convertToAssets or convertToShares instead. - * - * @return . The price per share. - */ - function pricePerShare() external view returns (uint256) { - StrategyData storage S = _strategyStorage(); - return _convertToAssets(S, 10 ** S.decimals, Math.Rounding.Down); - } + /** + * @notice Get the current address that can shutdown and emergency withdraw. + * @return . Address of the emergencyAdmin + */ + function emergencyAdmin() external view returns (address) { + return _strategyStorage().emergencyAdmin; + } - /** - * @notice To check if the strategy has been shutdown. - * @return . Whether or not the strategy is shutdown. - */ - function isShutdown() external view returns (bool) { - return _strategyStorage().shutdown; - } + /** + * @notice Get the current performance fee charged on profits. + * denominated in Basis Points where 10_000 == 100% + * @return . Current performance fee. + */ + function performanceFee() external view returns (uint16) { + return _strategyStorage().performanceFee; + } - /*////////////////////////////////////////////////////////////// - SETTER FUNCTIONS - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Step one of two to set a new address to be in charge of the strategy. - * @dev Can only be called by the current `management`. The address is - * set to pending management and will then have to call {acceptManagement} - * in order for the 'management' to officially change. - * - * Cannot set `management` to address(0). - * - * @param _management New address to set `pendingManagement` to. - */ - function setPendingManagement(address _management) external onlyManagement { - require(_management != address(0), "ZERO ADDRESS"); - _strategyStorage().pendingManagement = _management; - - emit UpdatePendingManagement(_management); - } + /** + * @notice Get the current address that receives the performance fees. + * @return . Address of performanceFeeRecipient + */ + function performanceFeeRecipient() external view returns (address) { + return _strategyStorage().performanceFeeRecipient; + } - /** - * @notice Step two of two to set a new 'management' of the strategy. - * @dev Can only be called by the current `pendingManagement`. - */ - function acceptManagement() external { - StrategyData storage S = _strategyStorage(); - require(msg.sender == S.pendingManagement, "!pending"); - S.management = msg.sender; - S.pendingManagement = address(0); - - emit UpdateManagement(msg.sender); + /** + * @notice Gets the current time profits are set to unlock over. + * @dev Returns `type(uint256).max` when the packed value was clamped. + * @return . The current profit max unlock time. + */ + function profitMaxUnlockTime() external view returns (uint256) { + uint256 _profitMaxUnlockTime = _strategyStorage().profitMaxUnlockTime; + if (_profitMaxUnlockTime == type(uint32).max) { + return type(uint256).max; } - /** - * @notice Sets a new address to be in charge of tend and reports. - * @dev Can only be called by the current `management`. - * - * @param _keeper New address to set `keeper` to. - */ - function setKeeper(address _keeper) external onlyManagement { - _strategyStorage().keeper = _keeper; + return _profitMaxUnlockTime; + } - emit UpdateKeeper(_keeper); - } + /** + * @notice The timestamp of the last report call. + * @return . The last report. + */ + function lastReport() external view returns (uint256) { + return uint256(_strategyStorage().lastReport); + } - /** - * @notice Sets a new address to be able to shutdown the strategy. - * @dev Can only be called by the current `management`. - * - * @param _emergencyAdmin New address to set `emergencyAdmin` to. - */ - function setEmergencyAdmin( - address _emergencyAdmin - ) external onlyManagement { - _strategyStorage().emergencyAdmin = _emergencyAdmin; - - emit UpdateEmergencyAdmin(_emergencyAdmin); - } + /** + * @notice The timestamp of the last accounting sync. + * @return . The last accrual. + */ + function lastAccrual() external view returns (uint256) { + return uint256(_strategyStorage().lastAccrual); + } - /** - * @notice Sets the performance fee to be charged on reported gains. - * @dev Can only be called by the current `management`. - * - * Denominated in Basis Points. So 100% == 10_000. - * Cannot set greater than to MAX_FEE. - * - * @param _performanceFee New performance fee. - */ - function setPerformanceFee(uint16 _performanceFee) external onlyManagement { - require(_performanceFee <= MAX_FEE, "MAX FEE"); - _strategyStorage().performanceFee = _performanceFee; - - emit UpdatePerformanceFee(_performanceFee); - } + /** + * @notice The last realized total assets baseline. + * @return . The last stored total assets. + */ + function lastTotalAssets() external view returns (uint256) { + return _strategyStorage().lastTotalAssets; + } - /** - * @notice Sets a new address to receive performance fees. - * @dev Can only be called by the current `management`. - * - * Cannot set to address(0). - * - * @param _performanceFeeRecipient New address to set `management` to. - */ - function setPerformanceFeeRecipient( - address _performanceFeeRecipient - ) external onlyManagement { - require(_performanceFeeRecipient != address(0), "ZERO ADDRESS"); - require(_performanceFeeRecipient != address(this), "Cannot be self"); - _strategyStorage().performanceFeeRecipient = _performanceFeeRecipient; - - emit UpdatePerformanceFeeRecipient(_performanceFeeRecipient); - } + /** + * @notice Gets the timestamp at which all reported profits will be unlocked. + * @return . The full profit unlocking timestamp. + */ + function fullProfitUnlockDate() external view returns (uint256) { + return uint256(_strategyStorage().fullProfitUnlockDate); + } - /** - * @notice Sets the time for profits to be unlocked over. - * @dev Can only be called by the current `management`. - * - * Denominated in seconds and cannot be greater than 1 year. - * - * NOTE: Setting to 0 will cause all currently locked profit - * to be unlocked instantly and should be done with care. - * - * `profitMaxUnlockTime` is stored as a uint32 for packing but can - * be passed in as uint256 for simplicity. - * - * @param _profitMaxUnlockTime New `profitMaxUnlockTime`. - */ - function setProfitMaxUnlockTime( - uint256 _profitMaxUnlockTime - ) external onlyManagement { - // Must be less than a year. - require(_profitMaxUnlockTime <= SECONDS_PER_YEAR, "too long"); - StrategyData storage S = _strategyStorage(); - - // If we are setting to 0 we need to adjust amounts. - if (_profitMaxUnlockTime == 0) { - uint256 shares = S.balances[address(this)]; - if (shares != 0) { - // Burn all shares if applicable. - _burn(S, address(this), shares); - } - // Reset unlocking variables - S.profitUnlockingRate = 0; - S.fullProfitUnlockDate = 0; - } + /** + * @notice The per second rate at which reported profits are unlocking. + * @return . The current profit unlocking rate. + */ + function profitUnlockingRate() external view returns (uint256) { + return _strategyStorage().profitUnlockingRate; + } - S.profitMaxUnlockTime = uint32(_profitMaxUnlockTime); + /** + * @notice Get the price per share. + * @dev This value offers limited precision. Integrations that require + * exact precision should use convertToAssets or convertToShares instead. + * + * @return . The price per share. + */ + function pricePerShare() external view returns (uint256) { + StrategyData storage S = _strategyStorage(); + return _convertToAssets(S, 10 ** S.decimals, Math.Rounding.Down); + } - emit UpdateProfitMaxUnlockTime(_profitMaxUnlockTime); - } + /** + * @notice To check if the strategy has been shutdown. + * @return . Whether or not the strategy is shutdown. + */ + function isShutdown() external view returns (bool) { + return _strategyStorage().shutdown; + } - /** - * @notice Updates the name for the strategy. - * @param _name The new name for the strategy. - */ - function setName(string calldata _name) external onlyManagement { - _strategyStorage().name = _name; - } + /** + * @notice To check if the strategy has been paused. + * @return . Whether or not the strategy is paused. + */ + function isPaused() external view returns (bool) { + return _strategyStorage().paused; + } - /*////////////////////////////////////////////////////////////// - ERC20 METHODS - //////////////////////////////////////////////////////////////*/ + /*////////////////////////////////////////////////////////////// + SETTER FUNCTIONS + //////////////////////////////////////////////////////////////*/ - /** - * @notice Returns the name of the token. - * @return . The name the strategy is using for its token. - */ - function name() external view returns (string memory) { - return _strategyStorage().name; - } + /** + * @notice Step one of two to set a new address to be in charge of the strategy. + * @dev Can only be called by the current `management`. The address is + * set to pending management and will then have to call {acceptManagement} + * in order for the 'management' to officially change. + * + * Cannot set `management` to address(0). + * + * @param _management New address to set `pendingManagement` to. + */ + function setPendingManagement(address _management) external onlyManagement { + require(_management != address(0), "ZERO ADDRESS"); + _strategyStorage().pendingManagement = _management; + + emit UpdatePendingManagement(_management); + } - /** - * @notice Returns the symbol of the strategies token. - * @dev Will be 'ys + asset symbol'. - * @return . The symbol the strategy is using for its tokens. - */ - function symbol() external view returns (string memory) { - return - string(abi.encodePacked("ys", _strategyStorage().asset.symbol())); - } + /** + * @notice Step two of two to set a new 'management' of the strategy. + * @dev Can only be called by the current `pendingManagement`. + */ + function acceptManagement() external { + StrategyData storage S = _strategyStorage(); + require(msg.sender == S.pendingManagement, "!pending"); + S.management = msg.sender; + S.pendingManagement = address(0); + + emit UpdateManagement(msg.sender); + } - /** - * @notice Returns the number of decimals used to get its user representation. - * @return . The decimals used for the strategy and `asset`. - */ - function decimals() external view returns (uint8) { - return _strategyStorage().decimals; - } + /** + * @notice Sets a new address to be in charge of tend and reports. + * @dev Can only be called by the current `management`. + * + * @param _keeper New address to set `keeper` to. + */ + function setKeeper(address _keeper) external onlyManagement { + _strategyStorage().keeper = _keeper; + + emit UpdateKeeper(_keeper); + } - /** - * @notice Returns the current balance for a given '_account'. - * @dev If the '_account` is the strategy then this will subtract - * the amount of shares that have been unlocked since the last profit first. - * @param account the address to return the balance for. - * @return . The current balance in y shares of the '_account'. - */ - function balanceOf(address account) external view returns (uint256) { - return _balanceOf(_strategyStorage(), account); - } + /** + * @notice Sets a new address to be able to shutdown the strategy. + * @dev Can only be called by the current `management`. + * + * @param _emergencyAdmin New address to set `emergencyAdmin` to. + */ + function setEmergencyAdmin( + address _emergencyAdmin + ) external onlyManagement { + _strategyStorage().emergencyAdmin = _emergencyAdmin; + + emit UpdateEmergencyAdmin(_emergencyAdmin); + } - /// @dev Internal implementation of {balanceOf}. - function _balanceOf( - StrategyData storage S, - address account - ) internal view returns (uint256) { - if (account == address(this)) { - return S.balances[account] - _unlockedShares(S); + /** + * @notice Sets the performance fee to be charged on reported gains. + * @dev Can only be called by the current `management`. + * + * Denominated in Basis Points. So 100% == 10_000. + * Cannot set greater than to MAX_FEE. + * + * @param _performanceFee New performance fee. + */ + function setPerformanceFee(uint16 _performanceFee) external onlyManagement { + _accrue(_strategyStorage()); + require(_performanceFee <= MAX_FEE, "MAX FEE"); + _strategyStorage().performanceFee = _performanceFee; + + emit UpdatePerformanceFee(_performanceFee); + } + + /** + * @notice Sets a new address to receive performance fees. + * @dev Can only be called by the current `management`. + * + * Cannot set to address(0). + * + * @param _performanceFeeRecipient New address to set `management` to. + */ + function setPerformanceFeeRecipient( + address _performanceFeeRecipient + ) external onlyManagement { + _accrue(_strategyStorage()); + require(_performanceFeeRecipient != address(0), "ZERO ADDRESS"); + require(_performanceFeeRecipient != address(this), "Cannot be self"); + _strategyStorage().performanceFeeRecipient = _performanceFeeRecipient; + + emit UpdatePerformanceFeeRecipient(_performanceFeeRecipient); + } + + /** + * @notice Sets the time for profits to be unlocked over. + * @dev Can only be called by the current `management`. + * + * NOTE: Setting to 0 will cause all currently locked profit + * to be unlocked instantly and should be done with care. + * + * `profitMaxUnlockTime` is packed as a `uint32`. Larger inputs are + * clamped to `type(uint32).max`, and the getter exposes that sentinel + * as `type(uint256).max`. + * + * @param _profitMaxUnlockTime New `profitMaxUnlockTime`. + */ + function setProfitMaxUnlockTime( + uint256 _profitMaxUnlockTime + ) external onlyManagement { + StrategyData storage S = _strategyStorage(); + _accrue(S); + + uint32 newProfitMaxUnlockTime = _profitMaxUnlockTime > type(uint32).max + ? type(uint32).max + : uint32(_profitMaxUnlockTime); + + if (newProfitMaxUnlockTime == 0) { + uint256 shares = S.balances[address(this)]; + if (shares != 0) { + _burn(S, address(this), shares); } - return S.balances[account]; + S.profitUnlockingRate = 0; + S.fullProfitUnlockDate = 0; } - /** - * @notice Transfer '_amount` of shares from `msg.sender` to `to`. - * @dev - * Requirements: - * - * - `to` cannot be the zero address. - * - `to` cannot be the address of the strategy. - * - the caller must have a balance of at least `_amount`. - * - * @param to The address shares will be transferred to. - * @param amount The amount of shares to be transferred from sender. - * @return . a boolean value indicating whether the operation succeeded. - */ - function transfer(address to, uint256 amount) external returns (bool) { - _transfer(_strategyStorage(), msg.sender, to, amount); - return true; - } + S.profitMaxUnlockTime = newProfitMaxUnlockTime; - /** - * @notice 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. - * @param owner The address who owns the shares. - * @param spender The address who would be moving the owners shares. - * @return . The remaining amount of shares of `owner` that could be moved by `spender`. - */ - function allowance( - address owner, - address spender - ) external view returns (uint256) { - return _allowance(_strategyStorage(), owner, spender); - } + emit UpdateProfitMaxUnlockTime(_profitMaxUnlockTime); + } - /// @dev Internal implementation of {allowance}. - function _allowance( - StrategyData storage S, - address owner, - address spender - ) internal view returns (uint256) { - return S.allowances[owner][spender]; - } + /** + * @notice Updates the name for the strategy. + * @param _name The new name for the strategy. + */ + function setName(string calldata _name) external onlyManagement { + _strategyStorage().name = _name; + } - /** - * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. - * @dev - * - * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on - * `transferFrom`. This is semantically equivalent to an infinite approval. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - * 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. - * - * @param spender the address to allow the shares to be moved by. - * @param amount the amount of shares to allow `spender` to move. - * @return . a boolean value indicating whether the operation succeeded. - */ - function approve(address spender, uint256 amount) external returns (bool) { - _approve(_strategyStorage(), msg.sender, spender, amount); - return true; - } + /*////////////////////////////////////////////////////////////// + ERC20 METHODS + //////////////////////////////////////////////////////////////*/ - /** - * @notice `amount` tokens from `from` to `to` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * @dev - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. - * - * NOTE: Does not update the allowance if the current allowance - * is the maximum `uint256`. - * - * Requirements: - * - * - `from` and `to` cannot be the zero address. - * - `to` cannot be the address of the strategy. - * - `from` must have a balance of at least `amount`. - * - the caller must have allowance for ``from``'s tokens of at least - * `amount`. - * - * Emits a {Transfer} event. - * - * @param from the address to be moving shares from. - * @param to the address to be moving shares to. - * @param amount the quantity of shares to move. - * @return . a boolean value indicating whether the operation succeeded. - */ - function transferFrom( - address from, - address to, - uint256 amount - ) external returns (bool) { - StrategyData storage S = _strategyStorage(); - _spendAllowance(S, from, msg.sender, amount); - _transfer(S, from, to, amount); - return true; - } + /** + * @notice Returns the name of the token. + * @return . The name the strategy is using for its token. + */ + function name() external view returns (string memory) { + return _strategyStorage().name; + } - /** - * @dev Moves `amount` of tokens from `from` to `to`. - * - * 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: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `to` cannot be the strategies address - * - `from` must have a balance of at least `amount`. - * - */ - function _transfer( - StrategyData storage S, - address from, - address to, - uint256 amount - ) internal { - require(from != address(0), "ERC20: transfer from the zero address"); - require(to != address(0), "ERC20: transfer to the zero address"); - require(to != address(this), "ERC20 transfer to strategy"); - - S.balances[from] -= amount; - unchecked { - S.balances[to] += amount; - } + /** + * @notice Returns the symbol of the strategies token. + * @dev Will be 'ys + asset symbol'. + * @return . The symbol the strategy is using for its tokens. + */ + function symbol() external view returns (string memory) { + return + string(abi.encodePacked("ys", _strategyStorage().asset.symbol())); + } - emit Transfer(from, to, amount); - } + /** + * @notice Returns the number of decimals used to get its user representation. + * @return . The decimals used for the strategy and `asset`. + */ + function decimals() external view returns (uint8) { + return _strategyStorage().decimals; + } - /** @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( - StrategyData storage S, - address account, - uint256 amount - ) internal { - require(account != address(0), "ERC20: mint to the zero address"); - - S.totalSupply += amount; - unchecked { - S.balances[account] += amount; - } - emit Transfer(address(0), account, amount); - } + /** + * @notice Returns the current balance for a given '_account'. + * @param account the address to return the balance for. + * @return . The current balance in y shares of the '_account'. + */ + function balanceOf(address account) external view returns (uint256) { + return _balanceOf(_strategyStorage(), account); + } - /** - * @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( - StrategyData storage S, - address account, - uint256 amount - ) internal { - require(account != address(0), "ERC20: burn from the zero address"); - - S.balances[account] -= amount; - unchecked { - S.totalSupply -= amount; - } - emit Transfer(account, address(0), amount); + /// @dev Internal implementation of {balanceOf}. + function _balanceOf( + StrategyData storage S, + address account + ) internal view returns (uint256) { + if (account == address(this)) { + return S.balances[account] - _unlockedShares(S); } + return S.balances[account]; + } - /** - * @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( - StrategyData storage S, - address owner, - address spender, - uint256 amount - ) internal { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - S.allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } + /** + * @notice Transfer '_amount` of shares from `msg.sender` to `to`. + * @dev + * Requirements: + * + * - `from` cannot be the address of the strategy. + * - `to` cannot be the zero address. + * - `to` cannot be the address of the strategy. + * - the caller must have a balance of at least `_amount`. + * + * @param to The address shares will be transferred to. + * @param amount The amount of shares to be transferred from sender. + * @return . a boolean value indicating whether the operation succeeded. + */ + function transfer(address to, uint256 amount) external returns (bool) { + _transfer(_strategyStorage(), msg.sender, to, amount); + return true; + } - /** - * @dev Updates `owner` s allowance for `spender` based on spent `amount`. - * - * Does not update the allowance amount in case of infinite allowance. - * Revert if not enough allowance is available. - * - * Might emit an {Approval} event. - */ - function _spendAllowance( - StrategyData storage S, - address owner, - address spender, - uint256 amount - ) internal { - uint256 currentAllowance = _allowance(S, owner, spender); - if (currentAllowance != type(uint256).max) { - require( - currentAllowance >= amount, - "ERC20: insufficient allowance" - ); - unchecked { - _approve(S, owner, spender, currentAllowance - amount); - } - } - } + /** + * @notice 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. + * @param owner The address who owns the shares. + * @param spender The address who would be moving the owners shares. + * @return . The remaining amount of shares of `owner` that could be moved by `spender`. + */ + function allowance( + address owner, + address spender + ) external view returns (uint256) { + return _allowance(_strategyStorage(), owner, spender); + } - /*////////////////////////////////////////////////////////////// - EIP-2612 LOGIC - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Returns the current nonce for `owner`. This value must be - * included whenever a signature is generated for {permit}. - * - * @dev Every successful call to {permit} increases ``owner``'s nonce by one. This - * prevents a signature from being used multiple times. - * - * @param _owner the address of the account to return the nonce for. - * @return . the current nonce for the account. - */ - function nonces(address _owner) external view returns (uint256) { - return _strategyStorage().nonces[_owner]; - } + /// @dev Internal implementation of {allowance}. + function _allowance( + StrategyData storage S, + address owner, + address spender + ) internal view returns (uint256) { + return S.allowances[owner][spender]; + } - /** - * @notice Sets `value` as the allowance of `spender` over ``owner``'s tokens, - * given ``owner``'s signed approval. - * - * @dev IMPORTANT: The same issues {IERC20-approve} has related to transaction - * ordering also apply here. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `deadline` must be a timestamp in the future. - * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` - * over the EIP712-formatted function arguments. - * - the signature must use ``owner``'s current nonce (see {nonces}). - * - * For more information on the signature format, see the - * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP - * section]. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external { - require(deadline >= block.timestamp, "ERC20: PERMIT_DEADLINE_EXPIRED"); - - // Unchecked because the only math done is incrementing - // the owner's nonce which cannot realistically overflow. - unchecked { - address recoveredAddress = ecrecover( - keccak256( - abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR(), - keccak256( - abi.encode( - keccak256( - "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" - ), - owner, - spender, - value, - _strategyStorage().nonces[owner]++, - deadline - ) - ) - ) - ), - v, - r, - s - ); + /** + * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. + * @dev + * + * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on + * `transferFrom`. This is semantically equivalent to an infinite approval. + * + * Requirements: + * + * - `spender` cannot be the zero address. + * + * 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. + * + * @param spender the address to allow the shares to be moved by. + * @param amount the amount of shares to allow `spender` to move. + * @return . a boolean value indicating whether the operation succeeded. + */ + function approve(address spender, uint256 amount) external returns (bool) { + _approve(_strategyStorage(), msg.sender, spender, amount); + return true; + } - require( - recoveredAddress != address(0) && recoveredAddress == owner, - "ERC20: INVALID_SIGNER" - ); + /** + * @notice `amount` tokens from `from` to `to` using the + * allowance mechanism. `amount` is then deducted from the caller's + * allowance. + * + * @dev + * Emits an {Approval} event indicating the updated allowance. This is not + * required by the EIP. + * + * NOTE: Does not update the allowance if the current allowance + * is the maximum `uint256`. + * + * Requirements: + * + * - `from` and `to` cannot be the zero address. + * - `from` cannot be the address of the strategy. + * - `to` cannot be the address of the strategy. + * - `from` must have a balance of at least `amount`. + * - the caller must have allowance for ``from``'s tokens of at least + * `amount`. + * + * Emits a {Transfer} event. + * + * @param from the address to be moving shares from. + * @param to the address to be moving shares to. + * @param amount the quantity of shares to move. + * @return . a boolean value indicating whether the operation succeeded. + */ + function transferFrom( + address from, + address to, + uint256 amount + ) external returns (bool) { + StrategyData storage S = _strategyStorage(); + _spendAllowance(S, from, msg.sender, amount); + _transfer(S, from, to, amount); + return true; + } + + /** + * @dev Moves `amount` of tokens from `from` to `to`. + * + * 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: + * + * - `from` cannot be the zero address. + * - `to` cannot be the zero address. + * - `from` cannot be the strategies address. + * - `to` cannot be the strategies address. + * - `from` must have a balance of at least `amount`. + * + */ + function _transfer( + StrategyData storage S, + address from, + address to, + uint256 amount + ) internal { + require(from != address(0), "ERC20: transfer from the zero address"); + require(to != address(0), "ERC20: transfer to the zero address"); + require(from != address(this), "ERC20 transfer from strategy"); + require(to != address(this), "ERC20 transfer to strategy"); + + S.balances[from] -= amount; + unchecked { + S.balances[to] += amount; + } + + emit Transfer(from, to, 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( + StrategyData storage S, + address account, + uint256 amount + ) internal { + require(account != address(0), "ERC20: mint to the zero address"); + + S.totalSupply += amount; + unchecked { + S.balances[account] += amount; + } + emit Transfer(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( + StrategyData storage S, + address account, + uint256 amount + ) internal { + require(account != address(0), "ERC20: burn from the zero address"); + + S.balances[account] -= amount; + unchecked { + S.totalSupply -= amount; + } + emit Transfer(account, address(0), amount); + } - _approve(_strategyStorage(), recoveredAddress, spender, value); + /** + * @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( + StrategyData storage S, + address owner, + address spender, + uint256 amount + ) internal { + require(owner != address(0), "ERC20: approve from the zero address"); + require(spender != address(0), "ERC20: approve to the zero address"); + + S.allowances[owner][spender] = amount; + emit Approval(owner, spender, amount); + } + + /** + * @dev Updates `owner` s allowance for `spender` based on spent `amount`. + * + * Does not update the allowance amount in case of infinite allowance. + * Revert if not enough allowance is available. + * + * Might emit an {Approval} event. + */ + function _spendAllowance( + StrategyData storage S, + address owner, + address spender, + uint256 amount + ) internal { + uint256 currentAllowance = _allowance(S, owner, spender); + if (currentAllowance != type(uint256).max) { + require( + currentAllowance >= amount, + "ERC20: insufficient allowance" + ); + unchecked { + _approve(S, owner, spender, currentAllowance - amount); } } + } - /** - * @notice Returns the domain separator used in the encoding of the signature - * for {permit}, as defined by {EIP712}. - * - * @return . The domain separator that will be used for any {permit} calls. - */ - function DOMAIN_SEPARATOR() public view returns (bytes32) { - return + /*////////////////////////////////////////////////////////////// + EIP-2612 LOGIC + //////////////////////////////////////////////////////////////*/ + + /** + * @notice Returns the current nonce for `owner`. This value must be + * included whenever a signature is generated for {permit}. + * + * @dev Every successful call to {permit} increases ``owner``'s nonce by one. This + * prevents a signature from being used multiple times. + * + * @param _owner the address of the account to return the nonce for. + * @return . the current nonce for the account. + */ + function nonces(address _owner) external view returns (uint256) { + return _strategyStorage().nonces[_owner]; + } + + /** + * @notice Sets `value` as the allowance of `spender` over ``owner``'s tokens, + * given ``owner``'s signed approval. + * + * @dev IMPORTANT: The same issues {IERC20-approve} has related to transaction + * ordering also apply here. + * + * Emits an {Approval} event. + * + * Requirements: + * + * - `spender` cannot be the zero address. + * - `deadline` must be a timestamp in the future. + * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` + * over the EIP712-formatted function arguments. + * - the signature must use ``owner``'s current nonce (see {nonces}). + * + * For more information on the signature format, see the + * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP + * section]. + */ + function permit( + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) external { + require(deadline >= block.timestamp, "ERC20: PERMIT_DEADLINE_EXPIRED"); + + // Unchecked because the only math done is incrementing + // the owner's nonce which cannot realistically overflow. + unchecked { + address recoveredAddress = ecrecover( keccak256( - abi.encode( + abi.encodePacked( + "\x19\x01", + DOMAIN_SEPARATOR(), keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ), - keccak256("Yearn Vault"), - keccak256(bytes(API_VERSION)), - block.chainid, - address(this) + abi.encode( + keccak256( + "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" + ), + owner, + spender, + value, + _strategyStorage().nonces[owner]++, + deadline + ) + ) ) - ); - } + ), + v, + r, + s + ); + + require( + recoveredAddress != address(0) && recoveredAddress == owner, + "ERC20: INVALID_SIGNER" + ); - /*////////////////////////////////////////////////////////////// - DEPLOYMENT - //////////////////////////////////////////////////////////////*/ - - /** - * @dev On contract creation we set `asset` for this contract to address(1). - * This prevents it from ever being initialized in the future. - * @param _factory Address of the factory of the same version for protocol fees. - */ - constructor(address _factory) { - FACTORY = _factory; - _strategyStorage().asset = ERC20(address(1)); + _approve(_strategyStorage(), recoveredAddress, spender, value); } } + + /** + * @notice Returns the domain separator used in the encoding of the signature + * for {permit}, as defined by {EIP712}. + * + * @return . The domain separator that will be used for any {permit} calls. + */ + function DOMAIN_SEPARATOR() public view returns (bytes32) { + return + keccak256( + abi.encode( + keccak256( + "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" + ), + keccak256("Yearn Vault"), + keccak256(bytes(API_VERSION)), + block.chainid, + address(this) + ) + ); + } + + /*////////////////////////////////////////////////////////////// + DEPLOYMENT + //////////////////////////////////////////////////////////////*/ + + /** + * @dev On contract creation we set `asset` for this contract to address(1). + * This prevents it from ever being initialized in the future. + * @param _factory Address of the factory of the same version for protocol fees. + */ + constructor(address _factory) { + FACTORY = _factory; + _strategyStorage().asset = ERC20(address(1)); + } +}