sUSD3

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/usd3/sUSD3.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.18;

import {BaseHooksUpgradeable, IERC20, IMorphoCredit, IProtocolConfig, Math, SafeERC20, USD3} from "./USD3.sol";
import {IStrategy} from "@tokenized-strategy/interfaces/IStrategy.sol";
import {ProtocolConfigLib} from "../libraries/ProtocolConfigLib.sol";

/**
 * @title sUSD3
 * @notice Subordinate tranche strategy that accepts USD3 deposits and provides levered yield
 * @dev Inherits from BaseHooksUpgradeable to maintain consistency with USD3 architecture
 *
 * Key features:
 * - Configurable lock period for new deposits (via ProtocolConfig)
 * - Configurable cooldown period (via ProtocolConfig) + withdrawal window (local management)
 * - Partial cooldown support for flexible withdrawals
 * - Cooldown updates overwrite previous settings
 * - First-loss absorption protects USD3 holders
 * - Maximum subordination ratio enforcement (via ProtocolConfig)
 * - Automatic yield distribution from USD3 strategy
 * - Dynamic parameter management through ProtocolConfig integration
 * - Full withdrawal clears both lock and cooldown states
 */
contract sUSD3 is BaseHooksUpgradeable {
    using Math for uint256;

    /*//////////////////////////////////////////////////////////////
                            STRUCTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Tracks user cooldown state (packed into single storage slot)
    struct UserCooldown {
        uint64 cooldownEnd; // When cooldown expires (8 bytes)
        uint64 windowEnd; // When withdrawal window closes (8 bytes)
        uint128 shares; // Shares locked for withdrawal (16 bytes)
    }

    /*//////////////////////////////////////////////////////////////
                            CONSTANTS
    //////////////////////////////////////////////////////////////*/

    // MAX_BPS is inherited from BaseHooksUpgradeable

    /*//////////////////////////////////////////////////////////////
                            STORAGE
    //////////////////////////////////////////////////////////////*/

    // Cooldown tracking
    mapping(address => UserCooldown) public cooldowns;
    mapping(address => uint256) public lockedUntil; // Initial lock tracking

    /// Whitelist of depositors allowed to 3rd party deposit
    mapping(address => bool) public depositorWhitelist;

    // Subordination management
    address public morphoCredit; // MorphoCredit address to access protocol config

    // Reserved for future use

    /*//////////////////////////////////////////////////////////////
                            EVENTS
    //////////////////////////////////////////////////////////////*/

    event CooldownStarted(address indexed user, uint256 shares, uint256 timestamp);
    event CooldownCancelled(address indexed user);
    event DepositorWhitelistUpdated(address indexed depositor, bool allowed);
    event WithdrawalCompleted(address indexed user, uint256 shares, uint256 assets);

    /*//////////////////////////////////////////////////////////////
                            INITIALIZATION
    //////////////////////////////////////////////////////////////*/

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initialize the sUSD3 strategy
     * @param _usd3Token Address of USD3 token (the asset)
     * @param _management Management address
     * @param _keeper Keeper address
     */
    function initialize(address _usd3Token, address _management, address _keeper) external initializer {
        // Initialize BaseStrategy with USD3 as the asset
        // Use management as performance fee recipient (fees will never be charged)
        __BaseStrategy_init(_usd3Token, "sUSD3", _management, _management, _keeper);

        // Get MorphoCredit address from USD3 strategy
        morphoCredit = address(USD3(_usd3Token).morphoCredit());
    }

    /**
     * @notice Get the symbol for the sUSD3 token
     * @return Symbol string "sUSD3"
     */
    function symbol() external pure returns (string memory) {
        return "sUSD3";
    }

    /*//////////////////////////////////////////////////////////////
                        CORE STRATEGY FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @dev sUSD3 holds USD3 tokens directly without deploying elsewhere
    /// @param _amount Amount to deploy (unused)
    function _deployFunds(uint256 _amount) internal override {
        // USD3 tokens stay in strategy (not deployed elsewhere)
        // Lock tracking is handled in deposit/mint overrides
    }

    /// @dev Funds are always available as USD3 tokens are held directly
    /// @param _amount Amount to free (unused)
    function _freeFunds(uint256 _amount) internal override {
        // Funds are already in the strategy, nothing to do
        // This is called during withdrawals but cooldown is enforced elsewhere
    }

    /// @dev Returns USD3 balance; yield is automatically received as USD3 mints shares to us
    /// @return Total USD3 tokens held by the strategy
    function _harvestAndReport() internal override returns (uint256) {
        // USD3 automatically mints shares to us during its report()
        // We just need to return our current balance
        // Any yield received is reflected in our USD3 token balance
        return asset.balanceOf(address(this));
    }

    /*//////////////////////////////////////////////////////////////
                        HOOKS IMPLEMENTATION
    //////////////////////////////////////////////////////////////*/

    /// @dev Pre-deposit hook to track lock period (handles both deposit and mint)
    function _preDepositHook(uint256 assets, uint256 shares, address receiver) internal override {
        if (assets == 0 && shares > 0) {
            assets = TokenizedStrategy.previewMint(shares);
        }

        // Prevent lock bypass and griefing attacks
        // Only allow self-deposits or whitelisted depositors
        require(
            msg.sender == receiver || depositorWhitelist[msg.sender], "sUSD3: Only self or whitelisted deposits allowed"
        );

        // Always extend lock period for valid deposits
        if (assets > 0 || shares > 0) {
            // Read lock duration from ProtocolConfig
            uint256 duration = lockDuration();
            lockedUntil[receiver] = block.timestamp + duration;
        }
    }

    /// @dev Post-withdraw hook to update cooldown after successful withdrawal
    function _postWithdrawHook(uint256 assets, uint256 shares, address receiver, address owner, uint256 maxLoss)
        internal
        override
    {
        // Update cooldown after successful withdrawal
        UserCooldown storage cooldown = cooldowns[owner];
        if (cooldown.shares > 0) {
            if (shares >= cooldown.shares) {
                // Full withdrawal - clear the cooldown
                delete cooldowns[owner];
            } else {
                // Partial withdrawal - reduce cooldown shares
                cooldown.shares -= uint128(shares);
            }
            emit WithdrawalCompleted(owner, shares, assets);
        }

        // Clear lock timestamp if fully withdrawn
        if (TokenizedStrategy.balanceOf(owner) == 0) {
            delete lockedUntil[owner];
        }
    }

    /**
     * @notice Prevent transfers during lock period or active cooldown
     * @dev Override from BaseHooksUpgradeable to enforce lock and cooldown
     * @param from Address transferring shares
     * @param to Address receiving shares
     * @param amount Amount of shares being transferred
     */
    function _preTransferHook(address from, address to, uint256 amount) internal override {
        // Allow minting (from == 0) and burning (to == 0)
        if (from == address(0) || to == address(0)) return;

        // Check lock period
        require(block.timestamp >= lockedUntil[from], "sUSD3: Cannot transfer during lock period");

        // Check if user has active cooldown
        UserCooldown memory cooldown = cooldowns[from];
        if (cooldown.shares > 0) {
            // User has shares in cooldown, check if trying to transfer them
            // Note: 'this' refers to the sUSD3 strategy contract
            uint256 userBalance = IERC20(address(this)).balanceOf(from);
            uint256 nonCooldownShares = userBalance > cooldown.shares ? userBalance - cooldown.shares : 0;

            // Only allow transfer of non-cooldown shares
            require(amount <= nonCooldownShares, "sUSD3: Cannot transfer shares in cooldown");
        }
    }

    /*//////////////////////////////////////////////////////////////
                        COOLDOWN FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Start cooldown for withdrawal
     * @param shares Number of shares to cooldown for withdrawal
     */
    function startCooldown(uint256 shares) external {
        require(shares > 0, "Invalid shares");
        require(block.timestamp >= lockedUntil[msg.sender], "Still in lock period");

        // Validate shares against actual balance
        uint256 userBalance = IERC20(address(this)).balanceOf(msg.sender);
        require(shares <= userBalance, "Insufficient balance for cooldown");

        // Read cooldown duration from ProtocolConfig
        uint256 cooldownPeriod = cooldownDuration();

        // Allow updating cooldown with new amount (overwrites previous)
        cooldowns[msg.sender] = UserCooldown({
            cooldownEnd: uint64(block.timestamp + cooldownPeriod),
            windowEnd: uint64(block.timestamp + cooldownPeriod + withdrawalWindow()),
            shares: uint128(shares)
        });

        emit CooldownStarted(msg.sender, shares, block.timestamp);
    }

    /**
     * @notice Cancel active cooldown
     * @dev Resets cooldown state, requiring user to start new cooldown to withdraw
     */
    function cancelCooldown() external {
        require(cooldowns[msg.sender].shares > 0, "No active cooldown");
        delete cooldowns[msg.sender];
        emit CooldownCancelled(msg.sender);
    }

    /*//////////////////////////////////////////////////////////////
                        VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @dev Enforces maximum subordination ratio based on market debt (actual or potential)
    /// @param _owner Address to check limit for
    /// @return Maximum deposit amount allowed
    function availableDepositLimit(address _owner) public view override returns (uint256) {
        // Get the subordinated debt cap in USDC terms
        uint256 subordinatedDebtCapUSDC = getSubordinatedDebtCapInUSDC();

        if (subordinatedDebtCapUSDC == 0) {
            // No debt to subordinate, no deposits needed
            return 0;
        }

        uint256 currentUSD3Holdings = asset.balanceOf(address(this));
        uint256 currentHoldingsUSDC = IStrategy(address(asset)).convertToAssets(currentUSD3Holdings);

        if (currentHoldingsUSDC >= subordinatedDebtCapUSDC) {
            // Already at or above the subordination cap
            return 0;
        }

        // Calculate remaining capacity in USDC terms
        uint256 remainingCapacityUSDC = subordinatedDebtCapUSDC - currentHoldingsUSDC;

        // Convert USDC capacity back to USD3 shares
        // This is the maximum USD3 tokens that can be deposited
        return IStrategy(address(asset)).convertToShares(remainingCapacityUSDC);
    }

    /// @dev Enforces lock period, cooldown, and withdrawal window requirements
    /// @param _owner Address to check limit for
    /// @return Maximum withdrawal amount allowed in assets
    function availableWithdrawLimit(address _owner) public view override returns (uint256) {
        // During shutdown, bypass all checks and return available assets
        if (TokenizedStrategy.isShutdown()) {
            // Return all available USD3 (entire balance since sUSD3 holds USD3 directly)
            return asset.balanceOf(address(this));
        }

        // Check initial lock period
        if (block.timestamp < lockedUntil[_owner]) {
            return 0;
        }

        UserCooldown memory cooldown = cooldowns[_owner];

        // No cooldown started - cannot withdraw
        if (cooldown.shares == 0) {
            return 0;
        }

        // Still in cooldown period
        if (block.timestamp < cooldown.cooldownEnd) {
            return 0;
        }

        // Window expired - must restart cooldown
        if (block.timestamp > cooldown.windowEnd) {
            return 0;
        }

        // Within valid withdrawal window - check backing requirement
        uint256 cooldownAmount = TokenizedStrategy.convertToAssets(cooldown.shares);

        uint256 subordinatedDebtFloorUSDC = getSubordinatedDebtFloorInUSDC();

        if (subordinatedDebtFloorUSDC == 0) {
            return cooldownAmount;
        }

        uint256 currentUSD3Holdings = asset.balanceOf(address(this));
        uint256 currentAssetsUSDC = IStrategy(address(asset)).convertToAssets(currentUSD3Holdings);

        if (currentAssetsUSDC <= subordinatedDebtFloorUSDC) {
            // Cannot withdraw without going below minimum backing
            return 0;
        }

        // Calculate maximum withdrawable while maintaining backing
        uint256 maxWithdrawable = currentAssetsUSDC - subordinatedDebtFloorUSDC;

        // Convert back to USD3 shares for withdrawal
        uint256 maxWithdrawableUSD3 = IStrategy(address(asset)).convertToShares(maxWithdrawable);

        // Return minimum of cooldown amount and max withdrawable
        return Math.min(cooldownAmount, maxWithdrawableUSD3);
    }

    /**
     * @notice Get user's cooldown status
     * @param user Address to check
     * @return cooldownEnd When cooldown expires (0 if no cooldown)
     * @return windowEnd When withdrawal window closes
     * @return shares Number of shares in cooldown
     */
    function getCooldownStatus(address user)
        external
        view
        returns (uint256 cooldownEnd, uint256 windowEnd, uint256 shares)
    {
        UserCooldown memory cooldown = cooldowns[user];
        return (cooldown.cooldownEnd, cooldown.windowEnd, cooldown.shares);
    }

    /*//////////////////////////////////////////////////////////////
                        MANAGEMENT FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Get the lock duration from ProtocolConfig
     * @return Lock duration in seconds
     */
    function lockDuration() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(morphoCredit).protocolConfig());

        uint256 duration = config.getSusd3LockDuration();
        return duration > 0 ? duration : 90 days; // Default to 90 days if not set
    }

    /**
     * @notice Get the cooldown duration from ProtocolConfig
     * @return Cooldown duration in seconds
     */
    function cooldownDuration() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(morphoCredit).protocolConfig());

        uint256 duration = config.getSusd3CooldownPeriod();
        return duration > 0 ? duration : 7 days; // Default to 7 days if not set
    }

    /**
     * @notice Get the withdrawal window from ProtocolConfig
     * @return Withdrawal window duration in seconds
     */
    function withdrawalWindow() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(morphoCredit).protocolConfig());
        uint256 window = config.getSusd3WithdrawalWindow();
        return window > 0 ? window : 2 days; // Default to 2 days if not set
    }

    /**
     * @notice Update depositor whitelist status for an address
     * @param _depositor Address to update
     * @param _allowed True to allow extending lock periods, false to disallow
     */
    function setDepositorWhitelist(address _depositor, bool _allowed) external onlyManagement {
        depositorWhitelist[_depositor] = _allowed;
        emit DepositorWhitelistUpdated(_depositor, _allowed);
    }

    /*//////////////////////////////////////////////////////////////
                    SUBORDINATION CALCULATION FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Get the maximum subordination ratio from ProtocolConfig
     * @return Maximum subordination ratio in basis points (e.g., 1500 = 15%)
     */
    function maxSubordinationRatio() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(morphoCredit).protocolConfig());
        uint256 ratio = config.getTrancheRatio();
        return ratio > 0 ? ratio : 1500; // Default to 15% if not set
    }

    /**
     * @notice Get the minimum backing ratio from ProtocolConfig
     * @return Minimum backing ratio in basis points
     */
    function minBackingRatio() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(morphoCredit).protocolConfig());
        return config.config(ProtocolConfigLib.MIN_SUSD3_BACKING_RATIO);
    }

    /**
     * @notice Calculate maximum sUSD3 deposits allowed based on debt and subordination ratio
     * @dev Returns the cap amount for subordinated debt based on actual or potential market debt
     * @return Maximum subordinated debt cap, expressed in USDC
     */
    function getSubordinatedDebtCapInUSDC() public view returns (uint256) {
        USD3 usd3 = USD3(address(asset));

        // Get actual borrowed amount
        (,, uint256 totalBorrowAssetsWaUSDC,) = usd3.getMarketLiquidity();
        uint256 actualDebtUSDC = usd3.WAUSDC().convertToAssets(totalBorrowAssetsWaUSDC);

        // Get potential debt based on debt ceiling
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(morphoCredit).protocolConfig());
        uint256 debtCap = config.config(ProtocolConfigLib.DEBT_CAP);

        uint256 potentialDebtUSDC;
        if (debtCap > 0) {
            potentialDebtUSDC = usd3.WAUSDC().convertToAssets(debtCap);
        }
        uint256 maxDebtUSDC = Math.max(actualDebtUSDC, potentialDebtUSDC);

        if (maxDebtUSDC == 0) {
            return 0; // No debt to subordinate
        }

        uint256 maxSubRatio = maxSubordinationRatio(); // e.g., 1500 (15%)

        // Cap on subordinated debt = max(actual, potential) * subordination ratio
        return (maxDebtUSDC * maxSubRatio) / MAX_BPS;
    }

    /**
     * @notice Calculate minimum sUSD3 backing required for current market debt
     * @dev Returns the floor amount of sUSD3 assets needed based on MIN_SUSD3_BACKING_RATIO
     * @return Minimum backing amount required, expressed in USDC
     */
    function getSubordinatedDebtFloorInUSDC() public view returns (uint256) {
        // Get minimum backing ratio
        uint256 backingRatio = minBackingRatio();

        // If backing ratio is 0, no minimum backing required
        if (backingRatio == 0) return 0;

        USD3 usd3 = USD3(address(asset));

        // Get actual borrowed amount
        (,, uint256 totalBorrowAssetsWaUSDC,) = usd3.getMarketLiquidity();
        uint256 debtUSDC = usd3.WAUSDC().convertToAssets(totalBorrowAssetsWaUSDC);

        // Calculate minimum required backing
        return (debtUSDC * backingRatio) / MAX_BPS;
    }

    /*//////////////////////////////////////////////////////////////
                        STORAGE GAP
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     */
    uint256[40] private __gap;
}
"
    },
    "src/usd3/USD3.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.22;

import {BaseHooksUpgradeable} from "./base/BaseHooksUpgradeable.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "../../lib/openzeppelin/contracts/utils/math/Math.sol";
import {IMorpho, IMorphoCredit, MarketParams, Id} from "../interfaces/IMorpho.sol";
import {MorphoLib} from "../libraries/periphery/MorphoLib.sol";
import {MorphoBalancesLib} from "../libraries/periphery/MorphoBalancesLib.sol";
import {SharesMathLib} from "../libraries/SharesMathLib.sol";
import {IERC4626} from "../../lib/openzeppelin/contracts/interfaces/IERC4626.sol";
import {Pausable} from "../../lib/openzeppelin/contracts/utils/Pausable.sol";
import {TokenizedStrategyStorageLib, ERC20} from "@periphery/libraries/TokenizedStrategyStorageLib.sol";
import {IProtocolConfig} from "../interfaces/IProtocolConfig.sol";
import {ProtocolConfigLib} from "../libraries/ProtocolConfigLib.sol";

/**
 * @title USD3
 * @author 3Jane Protocol
 * @notice Senior tranche strategy for USDC-based lending on 3Jane's credit markets
 * @dev Implements Yearn V3 tokenized strategy pattern for unsecured lending via MorphoCredit.
 * Deploys USDC capital to 3Jane's modified Morpho Blue markets that use credit-based
 * underwriting instead of collateral. Features first-loss protection through sUSD3
 * subordinate tranche absorption.
 *
 * Key features:
 * - Senior tranche with first-loss protection from sUSD3 holders
 * - Configurable deployment ratio to credit markets (maxOnCredit)
 * - Automatic yield distribution to sUSD3 via performance fees
 * - Loss absorption through direct share burning of sUSD3 holdings
 * - Commitment period enforcement for deposits
 * - Optional whitelist for controlled access
 * - Dynamic fee adjustment via ProtocolConfig integration
 *
 * Yield Distribution Mechanism:
 * - Tranche share distributed to sUSD3 holders via TokenizedStrategy's performance fee
 * - Performance fee can be set from 0-100% through syncTrancheShare()
 * - Direct storage manipulation bypasses TokenizedStrategy's 50% fee limit
 * - Keeper-controlled updates ensure protocol-wide consistency
 *
 * Loss Absorption Mechanism:
 * - When losses occur, sUSD3 shares are burned first (subordination)
 * - Direct storage manipulation used to burn shares without asset transfers
 * - USD3 holders protected up to total sUSD3 holdings
 * - Losses exceeding sUSD3 balance shared proportionally among USD3 holders
 */
contract USD3 is BaseHooksUpgradeable {
    using SafeERC20 for IERC20;
    using MorphoLib for IMorpho;
    using MorphoBalancesLib for IMorpho;
    using SharesMathLib for uint256;
    using Math for uint256;

    /*//////////////////////////////////////////////////////////////
                        CONSTANTS
    //////////////////////////////////////////////////////////////*/
    IERC4626 public constant WAUSDC = IERC4626(0xD4fa2D31b7968E448877f69A96DE69f5de8cD23E);

    /*//////////////////////////////////////////////////////////////
                        STORAGE - MORPHO PARAMETERS
    //////////////////////////////////////////////////////////////*/
    /// @notice MorphoCredit contract for lending operations
    IMorpho public morphoCredit;

    /// @notice Market ID for the lending market this strategy uses
    Id public marketId;

    /// @notice Market parameters for the lending market
    MarketParams internal _marketParams;

    /*//////////////////////////////////////////////////////////////
                        UPGRADEABLE STORAGE
    //////////////////////////////////////////////////////////////*/
    /// @notice Address of the subordinate sUSD3 strategy
    /// @dev Used for loss absorption and yield distribution
    address public sUSD3;

    /// @notice Whether whitelist is enforced for deposits
    bool public whitelistEnabled;

    /// @notice Whitelist status for addresses
    mapping(address => bool) public whitelist;

    /// @notice Whitelist of depositors allowed to 3rd party deposit
    mapping(address => bool) public depositorWhitelist;

    /// @notice Minimum deposit amount required
    uint256 public minDeposit;

    /// @notice Timestamp of last deposit for each user
    /// @dev Used to enforce commitment periods
    mapping(address => uint256) public depositTimestamp;

    /*//////////////////////////////////////////////////////////////
                            EVENTS
    //////////////////////////////////////////////////////////////*/
    event SUSD3StrategyUpdated(address oldStrategy, address newStrategy);
    event WhitelistUpdated(address indexed user, bool allowed);
    event DepositorWhitelistUpdated(address indexed depositor, bool allowed);
    event MinDepositUpdated(uint256 newMinDeposit);
    event TrancheShareSynced(uint256 trancheShare);

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initialize the USD3 strategy
     * @param _morphoCredit Address of the MorphoCredit lending contract
     * @param _marketId Market ID for the lending market
     * @param _management Management address for the strategy
     * @param _keeper Keeper address for automated operations
     */
    function initialize(address _morphoCredit, Id _marketId, address _management, address _keeper)
        external
        initializer
    {
        require(_morphoCredit != address(0), "!morpho");

        morphoCredit = IMorpho(_morphoCredit);
        marketId = _marketId;

        // Get and cache market params
        MarketParams memory params = morphoCredit.idToMarketParams(_marketId);
        require(params.loanToken != address(0), "Invalid market");
        _marketParams = params;

        // Initialize BaseStrategy with management as temporary performanceFeeRecipient
        // It will be updated to sUSD3 address after sUSD3 is deployed
        __BaseStrategy_init(params.loanToken, "USD3", _management, _management, _keeper);

        // Approve Morpho
        IERC20(asset).forceApprove(address(morphoCredit), type(uint256).max);
    }

    /**
     * @notice Reinitialize the USD3 strategy to switch asset from waUSDC to USDC
     * @dev This function is called during the upgrade from the previous USD3 implementation.
     *      The upgrade process MUST follow this sequence to prevent user losses:
     *      1. Set performance fee to 0 (via setPerformanceFee)
     *      2. Set profit unlock time to 0 (via setProfitMaxUnlockTime)
     *      3. Call report() on OLD implementation to finalize state before upgrade
     *      4. Upgrade proxy to new implementation
     *      5. Call reinitialize() to switch the underlying asset
     *      6. Call report() on NEW implementation to update totalAssets with new asset
     *      7. Call syncTrancheShare() to restore performance fees
     *      8. Restore profit unlock time to previous value
     *      This ensures totalAssets reflects the true USDC value before users can withdraw.
     *      Without both report() calls, users would lose value as totalAssets would not
     *      account for waUSDC appreciation or the asset switch.
     */
    function reinitialize() external reinitializer(2) {
        address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
        asset = ERC20(usdc);
        TokenizedStrategyStorageLib.StrategyData storage strategyData = TokenizedStrategyStorageLib.getStrategyStorage();
        strategyData.asset = ERC20(usdc);
        IERC20(usdc).forceApprove(address(WAUSDC), type(uint256).max);
    }

    /*//////////////////////////////////////////////////////////////
                        EXTERNAL VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Get the symbol for the USD3 token
     * @return Symbol string "USD3"
     */
    function symbol() external pure returns (string memory) {
        return "USD3";
    }

    /**
     * @notice Get the market parameters for this strategy
     * @return MarketParams struct containing lending market configuration
     */
    function marketParams() external view returns (MarketParams memory) {
        return _marketParams;
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev Get current market liquidity information
     * @return totalSupplyAssets Total assets supplied to the market
     * @return totalShares Total supply shares in the market
     * @return totalBorrowAssets Total assets borrowed from the market
     * @return waUSDCLiquidity Available liquidity in the market
     */
    function getMarketLiquidity()
        public
        view
        returns (uint256 totalSupplyAssets, uint256 totalShares, uint256 totalBorrowAssets, uint256 waUSDCLiquidity)
    {
        (totalSupplyAssets, totalShares, totalBorrowAssets,) = morphoCredit.expectedMarketBalances(_marketParams);
        waUSDCLiquidity = totalSupplyAssets > totalBorrowAssets ? totalSupplyAssets - totalBorrowAssets : 0;
    }

    /**
     * @dev Get strategy's position in the market
     * @return shares Number of supply shares held
     * @return waUSDCMax Maximum waUSDC that can be withdrawn
     * @return waUSDCLiquidity Available market liquidity in waUSDC
     */
    function getPosition() internal view returns (uint256 shares, uint256 waUSDCMax, uint256 waUSDCLiquidity) {
        shares = morphoCredit.position(marketId, address(this)).supplyShares;
        uint256 totalSupplyAssets;
        uint256 totalShares;
        (totalSupplyAssets, totalShares,, waUSDCLiquidity) = getMarketLiquidity();
        waUSDCMax = shares.toAssetsDown(totalSupplyAssets, totalShares);
    }

    /*//////////////////////////////////////////////////////////////
                    INTERNAL STRATEGY FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @dev Deploy funds to MorphoCredit market respecting maxOnCredit ratio
    /// @param _amount Amount of asset to deploy
    function _deployFunds(uint256 _amount) internal override {
        if (_amount == 0) return;

        // Wrap USDC to waUSDC
        _amount = WAUSDC.deposit(_amount, address(this));

        uint256 maxOnCreditRatio = maxOnCredit();
        if (maxOnCreditRatio == 0) {
            // Don't deploy anything when set to 0%, keep all waUSDC local
            return;
        }

        // Calculate total waUSDC (deployed + local)
        uint256 deployedWaUSDC = suppliedWaUSDC();
        uint256 localWaUSDC = balanceOfWaUSDC();
        uint256 totalWaUSDC = deployedWaUSDC + localWaUSDC;

        // Calculate max that should be deployed to MorphoCredit
        uint256 maxDeployableWaUSDC = (totalWaUSDC * maxOnCreditRatio) / 10_000;

        if (maxDeployableWaUSDC <= deployedWaUSDC) {
            // Already at or above max, keep all new waUSDC local
            return;
        }

        // Deploy only the amount needed to reach max
        uint256 waUSDCToSupply = Math.min(localWaUSDC, maxDeployableWaUSDC - deployedWaUSDC);

        _supplyToMorpho(waUSDCToSupply);
    }

    /// @dev Withdraw funds from MorphoCredit market
    /// @param _amount Amount of asset to free up
    function _freeFunds(uint256 _amount) internal override {
        if (_amount == 0) {
            return;
        }

        // Calculate how much waUSDC we need
        uint256 waUSDCNeeded = WAUSDC.previewWithdraw(_amount);

        // Check local waUSDC balance first
        uint256 localWaUSDC = balanceOfWaUSDC();

        if (localWaUSDC < waUSDCNeeded) {
            // Need to withdraw from MorphoCredit
            uint256 waUSDCToWithdraw = waUSDCNeeded - localWaUSDC;

            uint256 withdrawn = _withdrawFromMorpho(waUSDCToWithdraw);

            if (withdrawn > 0) {
                localWaUSDC = balanceOfWaUSDC();
            }
        }

        uint256 waUSDCToUnwrap = Math.min(localWaUSDC, waUSDCNeeded);

        if (waUSDCToUnwrap > 0) {
            WAUSDC.redeem(waUSDCToUnwrap, address(this), address(this));
        }
    }

    /// @dev Emergency withdraw function to free funds from MorphoCredit
    /// @param amount The amount to withdraw (use type(uint256).max for all)
    function _emergencyWithdraw(uint256 amount) internal override {
        // This is called during shutdown to free funds from Morpho
        // Use _freeFunds which already handles the withdrawal logic
        _freeFunds(amount);
    }

    /// @dev Harvest interest from MorphoCredit and report total assets
    /// @return Total assets held by the strategy
    function _harvestAndReport() internal override returns (uint256) {
        MarketParams memory params = _marketParams;

        morphoCredit.accrueInterest(params);

        _tend(asset.balanceOf(address(this)));

        uint256 totalWaUSDC = suppliedWaUSDC() + balanceOfWaUSDC();

        return WAUSDC.convertToAssets(totalWaUSDC) + asset.balanceOf(address(this));
    }

    /// @dev Rebalances between idle and deployed funds to maintain maxOnCredit ratio
    /// @param _totalIdle Current idle funds available
    function _tend(uint256 _totalIdle) internal virtual override {
        // First wrap any idle USDC to waUSDC
        if (_totalIdle > 0) {
            WAUSDC.deposit(_totalIdle, address(this));
        }

        // Calculate based on waUSDC amounts
        uint256 deployedWaUSDC = suppliedWaUSDC();
        uint256 localWaUSDC = balanceOfWaUSDC();
        uint256 totalWaUSDC = deployedWaUSDC + localWaUSDC;

        uint256 targetDeployedWaUSDC = (totalWaUSDC * maxOnCredit()) / 10_000;

        if (deployedWaUSDC > targetDeployedWaUSDC) {
            // Withdraw excess from MorphoCredit
            uint256 waUSDCToWithdraw = deployedWaUSDC - targetDeployedWaUSDC;
            _withdrawFromMorpho(waUSDCToWithdraw);
        } else if (targetDeployedWaUSDC > deployedWaUSDC && localWaUSDC > 0) {
            // Deploy more if we have local waUSDC
            uint256 waUSDCToDeploy = Math.min(localWaUSDC, targetDeployedWaUSDC - deployedWaUSDC);
            _supplyToMorpho(waUSDCToDeploy);
        }
    }

    /// @dev Helper function to supply waUSDC to MorphoCredit
    /// @param amount Amount of waUSDC to supply
    /// @return supplied Actual amount supplied (for consistency with withdraw helper)
    function _supplyToMorpho(uint256 amount) internal returns (uint256 supplied) {
        if (amount == 0) return 0;

        morphoCredit.supply(_marketParams, amount, 0, address(this), "");
        return amount;
    }

    /// @dev Helper function to withdraw waUSDC from MorphoCredit
    /// @param amountRequested Amount of waUSDC to withdraw
    /// @return amountWithdrawn Actual amount withdrawn (may be less than requested)
    function _withdrawFromMorpho(uint256 amountRequested) internal returns (uint256 amountWithdrawn) {
        if (amountRequested == 0) return 0;

        morphoCredit.accrueInterest(_marketParams);
        (uint256 shares, uint256 waUSDCMax, uint256 waUSDCLiquidity) = getPosition();

        uint256 availableWaUSDC = Math.min(waUSDCMax, waUSDCLiquidity);

        if (availableWaUSDC == 0) {
            return 0;
        }

        amountWithdrawn = Math.min(amountRequested, availableWaUSDC);

        if (amountWithdrawn > 0) {
            if (amountWithdrawn >= waUSDCMax) {
                morphoCredit.withdraw(_marketParams, 0, shares, address(this), address(this));
            } else {
                morphoCredit.withdraw(_marketParams, amountWithdrawn, 0, address(this), address(this));
            }
        }

        return amountWithdrawn;
    }

    /*//////////////////////////////////////////////////////////////
                    PUBLIC VIEW FUNCTIONS (OVERRIDES)
    //////////////////////////////////////////////////////////////*/

    /// @dev Returns available withdraw limit, enforcing commitment time
    /// @param _owner Address to check limit for
    /// @return Maximum amount that can be withdrawn
    function availableWithdrawLimit(address _owner) public view override returns (uint256) {
        // Get available liquidity first
        uint256 idleAsset = asset.balanceOf(address(this));

        (, uint256 waUSDCMax, uint256 waUSDCLiquidity) = getPosition();

        uint256 availableWaUSDC;

        if (Pausable(address(WAUSDC)).paused()) {
            availableWaUSDC = 0;
        } else {
            uint256 localWaUSDC = Math.min(balanceOfWaUSDC(), WAUSDC.maxRedeem(address(this)));
            uint256 morphoWaUSDC = Math.min(waUSDCMax, waUSDCLiquidity);
            morphoWaUSDC = Math.min(morphoWaUSDC, WAUSDC.maxRedeem(address(morphoCredit)));
            availableWaUSDC = localWaUSDC + morphoWaUSDC;
        }

        uint256 availableLiquidity = idleAsset + WAUSDC.convertToAssets(availableWaUSDC);

        // During shutdown, bypass all checks
        if (TokenizedStrategy.isShutdown()) {
            return availableLiquidity;
        }

        // Check commitment time
        uint256 commitTime = minCommitmentTime();
        if (commitTime > 0) {
            uint256 depositTime = depositTimestamp[_owner];
            if (depositTime > 0 && block.timestamp < depositTime + commitTime) {
                return 0; // Commitment period not met
            }
        }

        return availableLiquidity;
    }

    /// @dev Returns available deposit limit, enforcing whitelist and supply cap
    /// @param _owner Address to check limit for
    /// @return Maximum amount that can be deposited
    function availableDepositLimit(address _owner) public view override returns (uint256) {
        // Check whitelist if enabled
        if (whitelistEnabled && !whitelist[_owner]) {
            return 0;
        }

        uint256 maxDeposit = WAUSDC.maxDeposit(address(this));

        if (Pausable(address(WAUSDC)).paused() || maxDeposit == 0) {
            return 0;
        }

        // Block deposits from borrowers
        if (morphoCredit.borrowShares(marketId, _owner) > 0) {
            return 0;
        }

        uint256 cap = supplyCap();
        if (cap == 0 || cap == type(uint256).max) {
            return type(uint256).max;
        }

        uint256 currentTotalAssets = TokenizedStrategy.totalAssets();
        if (cap <= currentTotalAssets) {
            return 0;
        }
        return Math.min(cap - currentTotalAssets, maxDeposit);
    }

    /*//////////////////////////////////////////////////////////////
                        HOOKS IMPLEMENTATION
    //////////////////////////////////////////////////////////////*/

    /// @dev Pre-deposit hook to enforce minimum deposit and track commitment time
    function _preDepositHook(uint256 assets, uint256 shares, address receiver) internal override {
        if (assets == 0 && shares > 0) {
            assets = TokenizedStrategy.previewMint(shares);
        }

        // Handle type(uint256).max case - resolve to actual balance
        if (assets == type(uint256).max) {
            assets = asset.balanceOf(msg.sender);
        }

        // Enforce minimum deposit only for first-time depositors
        uint256 currentBalance = TokenizedStrategy.balanceOf(receiver);
        if (currentBalance == 0) {
            require(assets >= minDeposit, "Below minimum deposit");
        }

        // Prevent commitment bypass and griefing attacks
        if (minCommitmentTime() > 0) {
            // Only allow self-deposits or whitelisted depositors
            require(
                msg.sender == receiver || depositorWhitelist[msg.sender],
                "USD3: Only self or whitelisted deposits allowed"
            );

            // Always extend commitment for valid deposits
            depositTimestamp[receiver] = block.timestamp;
        }
    }

    /// @dev Post-withdraw hook to clear commitment on full exit
    function _postWithdrawHook(uint256 assets, uint256 shares, address receiver, address owner, uint256 maxLoss)
        internal
        override
    {
        // Clear commitment timestamp if user fully exited
        if (TokenizedStrategy.balanceOf(owner) == 0) {
            delete depositTimestamp[owner];
        }
    }

    /// @dev Post-report hook to handle loss absorption by burning sUSD3's shares
    function _postReportHook(uint256 profit, uint256 loss) internal override {
        if (loss > 0 && sUSD3 != address(0)) {
            // Get sUSD3's current USD3 balance
            uint256 susd3Balance = TokenizedStrategy.balanceOf(sUSD3);

            if (susd3Balance > 0) {
                // Calculate how many shares are needed to cover the loss
                // IMPORTANT: We must use pre-report values to calculate the correct share amount
                // The report has already reduced totalAssets, so we add the loss back
                uint256 totalSupply = TokenizedStrategy.totalSupply();
                uint256 totalAssets = TokenizedStrategy.totalAssets();

                // Calculate shares to burn using pre-loss exchange rate
                uint256 sharesToBurn = loss.mulDiv(totalSupply, totalAssets + loss, Math.Rounding.Floor);

                // Cap at sUSD3's actual balance - they can't lose more than they have
                if (sharesToBurn > susd3Balance) {
                    sharesToBurn = susd3Balance;
                }

                if (sharesToBurn > 0) {
                    _burnSharesFromSusd3(sharesToBurn);
                }
            }
        }
    }

    /**
     * @notice Prevent transfers during commitment period
     * @dev Override from BaseHooksUpgradeable to enforce commitment
     * @param from Address transferring shares
     * @param to Address receiving shares
     * @param amount Amount of shares being transferred
     */
    function _preTransferHook(address from, address to, uint256 amount) internal override {
        // Allow minting (from == 0) and burning (to == 0)
        if (from == address(0) || to == address(0)) return;

        // Allow transfers to/from sUSD3 (staking and withdrawals)
        if (to == sUSD3 || from == sUSD3) return;

        // Check commitment period
        uint256 commitmentEnd = depositTimestamp[from] + minCommitmentTime();
        require(
            block.timestamp >= commitmentEnd || depositTimestamp[from] == 0,
            "USD3: Cannot transfer during commitment period"
        );
    }

    /*//////////////////////////////////////////////////////////////
                    INTERNAL HELPER FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev Directly burn shares from sUSD3's balance using storage manipulation
     *
     * IMPORTANT: Direct storage manipulation is necessary here because TokenizedStrategy
     * does not expose a public burn function. The only ways to burn shares in
     * TokenizedStrategy are through withdraw/redeem (which require asset transfers)
     * or internal profit/loss accounting. Since we need to burn sUSD3's shares
     * without triggering asset transfers, direct storage manipulation is the only
     * viable approach.
     *
     * @param amount Number of shares to burn from sUSD3
     */
    function _burnSharesFromSusd3(uint256 amount) internal {
        // Calculate storage slots using the library
        bytes32 totalSupplySlot = TokenizedStrategyStorageLib.totalSupplySlot();
        bytes32 balanceSlot = TokenizedStrategyStorageLib.balancesSlot(sUSD3);

        // Read current values
        uint256 currentBalance;
        uint256 currentTotalSupply;
        assembly {
            currentBalance := sload(balanceSlot)
            currentTotalSupply := sload(totalSupplySlot)
        }

        // Ensure we don't burn more than available
        uint256 actualBurn = amount;
        if (actualBurn > currentBalance) {
            actualBurn = currentBalance;
        }

        // Update storage
        assembly {
            sstore(balanceSlot, sub(currentBalance, actualBurn))
            sstore(totalSupplySlot, sub(currentTotalSupply, actualBurn))
        }

        // Emit Transfer event to address(0) for transparency
        emit IERC20.Transfer(sUSD3, address(0), actualBurn);
    }

    /*//////////////////////////////////////////////////////////////
                        PUBLIC VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Get the balance of waUSDC held locally (not deployed to MorphoCredit)
     * @return Amount of waUSDC held in this contract
     */
    function balanceOfWaUSDC() public view returns (uint256) {
        return WAUSDC.balanceOf(address(this));
    }

    /**
     * @notice Get the amount of waUSDC supplied to MorphoCredit
     * @return Amount of waUSDC deployed to the lending market
     */
    function suppliedWaUSDC() public view returns (uint256) {
        return morphoCredit.expectedSupplyAssets(_marketParams, address(this));
    }

    /**
     * @notice Get the maximum percentage of funds to deploy to credit markets from ProtocolConfig
     * @return Maximum deployment ratio in basis points (10000 = 100%)
     * @dev Returns the value from ProtocolConfig directly. If not configured in ProtocolConfig,
     *      it returns 0, effectively preventing deployment until explicitly configured.
     */
    function maxOnCredit() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(address(morphoCredit)).protocolConfig());
        return config.getMaxOnCredit();
    }

    /**
     * @notice Get the minimum commitment time from ProtocolConfig
     * @return Minimum commitment time in seconds
     */
    function minCommitmentTime() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(address(morphoCredit)).protocolConfig());
        return config.getUsd3CommitmentTime();
    }

    /**
     * @notice Get the supply cap from ProtocolConfig
     * @return Supply cap in asset units (0 means no cap)
     */
    function supplyCap() public view returns (uint256) {
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(address(morphoCredit)).protocolConfig());
        return config.config(ProtocolConfigLib.USD3_SUPPLY_CAP);
    }

    /*//////////////////////////////////////////////////////////////
                        MANAGEMENT FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Set the sUSD3 subordinate strategy address
     * @param _sUSD3 Address of the sUSD3 strategy
     * @dev Only callable by management. After calling, also set performance fee recipient.
     */
    function setSUSD3(address _sUSD3) external onlyManagement {
        require(sUSD3 == address(0), "sUSD3 already set");
        require(_sUSD3 != address(0), "Invalid address");

        sUSD3 = _sUSD3;
        emit SUSD3StrategyUpdated(address(0), _sUSD3);

        // NOTE: After calling this, management should also call:
        // ITokenizedStrategy(usd3Address).setPerformanceFeeRecipient(_sUSD3)
        // to ensure yield distribution goes to sUSD3
    }

    /**
     * @notice Enable or disable whitelist requirement
     * @param _enabled True to enable whitelist, false to disable
     */
    function setWhitelistEnabled(bool _enabled) external onlyManagement {
        whitelistEnabled = _enabled;
    }

    /**
     * @notice Update whitelist status for an address
     * @param _user Address to update
     * @param _allowed True to whitelist, false to remove from whitelist
     */
    function setWhitelist(address _user, bool _allowed) external onlyManagement {
        whitelist[_user] = _allowed;
        emit WhitelistUpdated(_user, _allowed);
    }

    /**
     * @notice Update depositor whitelist status for an address
     * @param _depositor Address to update
     * @param _allowed True to allow extending commitments, false to disallow
     */
    function setDepositorWhitelist(address _depositor, bool _allowed) external onlyManagement {
        depositorWhitelist[_depositor] = _allowed;
        emit DepositorWhitelistUpdated(_depositor, _allowed);
    }

    /**
     * @notice Set minimum deposit amount
     * @param _minDeposit Minimum amount required for deposits
     */
    function setMinDeposit(uint256 _minDeposit) external onlyManagement {
        minDeposit = _minDeposit;
        emit MinDepositUpdated(_minDeposit);
    }

    /*//////////////////////////////////////////////////////////////
                        KEEPER FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Sync the tranche share (performance fee) from ProtocolConfig
     * @dev Reads TRANCHE_SHARE_VARIANT from ProtocolConfig and updates local storage
     *
     * IMPORTANT: Direct storage manipulation is necessary here because TokenizedStrategy's
     * setPerformanceFee() function has a hardcoded MAX_FEE limit of 5000 (50%). Since we
     * need to support higher fee distributions to sUSD3 (potentially up to 100% for full
     * subordination scenarios), we must bypass this restriction by directly modifying the
     * storage slot.
     *
     * Storage layout in TokenizedStrategy (slot 9):
     * - Bits 0-31: profitMaxUnlockTime (uint32)
     * - Bits 32-47: performanceFee (uint16) <- We modify this
     * - Bits 48-207: performanceFeeRecipient (address)
     *
     * @dev Only callable by keepers to ensure controlled updates
     */
    function syncTrancheShare() external onlyKeepers {
        // Get the protocol config through MorphoCredit
        IProtocolConfig config = IProtocolConfig(IMorphoCredit(address(morphoCredit)).protocolConfig());

        // Read the tranche share variant (yield share to sUSD3 in basis points)
        uint256 trancheShare = config.getTrancheShareVariant();
        require(trancheShare <= 10_000, "Invalid tranche share");

        // Get the storage slot for performanceFee using the library
        bytes32 targetSlot = TokenizedStrategyStorageLib.profitConfigSlot();

        // Read current slot value
        uint256 currentSlotValue;
        assembly {
            currentSlotValue := sload(targetSlot)
        }

        // Clear the performanceFee bits (32-47) and set new value
        uint256 mask = ~(uint256(0xFFFF) << 32);
        uint256 newSlotValue = (currentSlotValue & mask) | (trancheShare << 32);

        // Write back to storage
        assembly {
            sstore(targetSlot, newSlotValue)
        }

        emit TrancheShareSynced(trancheShare);
    }

    /*//////////////////////////////////////////////////////////////
                        STORAGE GAP
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[40] private __gap;
}
"
    },
    "lib/tokenized-strategy/src/interfaces/IStrategy.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

import {ITokenizedStrategy} from "./ITokenizedStrategy.sol";
import {IBaseStrategy} from "./IBaseStrategy.sol";

interface IStrategy is IBaseStrategy, ITokenizedStrategy {}
"
    },
    "src/libraries/ProtocolConfigLib.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title ProtocolConfigLib
/// @notice Library containing all configuration keys for ProtocolConfig
/// @dev Centralizes all configuration keys to avoid magic strings and improve maintainability
library ProtocolConfigLib {
    // Market Control Keys
    bytes32 internal constant IS_PAUSED = keccak256("IS_PAUSED");
    bytes32 internal constant MAX_ON_CREDIT = keccak256("MAX_ON_CREDIT");
    bytes32 internal constant DEBT_CAP = keccak256("DEBT_CAP");

    // Credit Line Keys
    bytes32 internal constant MIN_LOAN_DURATION = keccak256("MIN_LOAN_DURATION");
    bytes32 internal constant LATE_REPAYMENT_THRESHOLD = keccak256("LATE_REPAYMENT_THRESHOLD");
    bytes32 internal constant DEFAULT_THRESHOLD = keccak256("DEFAULT_THRESHOLD");
    bytes32 internal constant GRACE_PERIOD = keccak256("GRACE_PERIOD");

    // Interest Rate Keys
    bytes32 internal constant MIN_RATE_AT_TARGET = keccak256("MIN_RATE_AT_TARGET");
    bytes32 internal constant MAX_RATE_AT_TARGET = keccak256("MAX_RATE_AT_TARGET");

    // Tranche Keys (USD3 & sUSD3)
    bytes32 internal constant TRANCHE_RATIO = keccak256("TRANCHE_RATIO");
    bytes32 internal constant TRANCHE_SHARE_VARIANT = keccak256("TRANCHE_SHARE_VARIANT");
    bytes32 internal constant MIN_SUSD3_BACKING_RATIO = keccak256("MIN_SUSD3_BACKING_RATIO");

    // Timing Keys
    bytes32 internal constant SUSD3_LOCK_DURATION = keccak256("SUSD3_LOCK_DURATION");
    bytes32 internal constant SUSD3_COOLDOWN_PERIOD = keccak256("SUSD3_COOLDOWN_PERIOD");
    bytes32 internal constant USD3_COMMITMENT_TIME = keccak256("USD3_COMMITMENT_TIME");
    bytes32 internal constant SUSD3_WITHDRAWAL_WINDOW = keccak256("SUSD3_WITHDRAWAL_WINDOW");

    // Supply Cap Keys
    bytes32 internal constant USD3_SUPPLY_CAP = keccak256("USD3_SUPPLY_CAP");

    // Markdown Keys
    bytes32 internal constant FULL_MARKDOWN_DURATION = keccak256("FULL_MARKDOWN_DURATION");
}
"
    },
    "src/usd3/base/BaseHooksUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

import {BaseStrategyUpgradeable} from "./BaseStrategyUpgradeable.sol";
import {Hooks} from "@periphery/Bases/Hooks/Hooks.sol";
import {ITokenizedStrategy} from "@tokenized-strategy/interfaces/ITokenizedStrategy.sol";

/**
 * @title BaseHooksUpgradeable
 * @author Yearn's BaseHooks adapted for upgradeable strategies
 * @notice This contract can be inherited by any strategy wishing to implement
 *         pre or post hooks for deposit, withdraw, transfer, or report functions.
 *
 *         This version:
 *         - Inherits from BaseStrategyUpgradeable instead of BaseHealthCheck
 *         - Uses Yearn's Hooks contract for standardized hook interfaces
 *         - Is compatible with upgradeable proxy patterns
 */
abstract contract BaseHooksUpgradeable is BaseStrategyUpgradeable, Hooks {
    /*//////////////////////////////////////////////////////////////
                            CONSTANTS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_BPS = 10_000;

    /*//////////////////////////////////////////////////////////////
                        OVERRIDDEN FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Deposit assets and receive shares
     * @param assets Amount of assets to deposit
     * @param receiver Address to receive the shares
     * @return shares Amount of shares minted
     */
    function deposit(uint256 assets, address receiver) external virtual returns (uint256 shares) {
        _preDepositHook(assets, shares, receiver);
        shares = abi.decode(
            _delegateCall(abi.encodeCall(ITokenizedStrategy(address(this)).deposit, (assets, receiver))), (uint256)
        );
        _postDepositHook(assets, shares, receiver);
    }

    /**
     * @notice Mint shares by depositing assets
     * @param shares Amount of shares to mint
     * @param receiver Address to receive the shares
     * @return assets Amount of assets deposited
     */
    function mint(uint256 shares, address receiver) external virtual returns (uint256 assets) {
        _preDepositHook(assets, shares, receiver);
        assets = abi.decode(
            _delegateCall(abi.encodeCall(ITokenizedStrategy(address(this)).mint, (shares, receiver))), (uint256)
        );
        _postDepositHook(assets, shares, receiver);
    }

    /**
     * @notice Withdraw assets by burning shares
     * @param assets Amount of assets to withdraw
     * @param receiver Address to receive the assets
     * @param owner Address whose shares are burned
     * @return shares Amount of shares burned
     */
    function withdraw(uint256 assets, address receiver, address owner) external virtual returns (uint256 shares) {
        return withdraw(assets, receiver, owner, 0);
    }

    /**
     * @notice Withdraw assets with custom max loss
     * @param assets Amount of assets to withdraw
     * @param receiver Address to receive the assets
     * @param owner Address whose shares are burned
     * @param maxLoss Maximum acceptable loss in basis points
     * @return shares Amount of shares burned
     */
    function withdraw(uint256 assets, address receiver, address owner, uint256 maxLoss)
        public
        virtual
        returns (uint256 shares)
    {
        _preWithdrawHook(assets, shares, receiver, owner, maxLoss);
        shares = abi.decode(
            _delegateCall(
                abi.encodeWithSelector(ITokenizedStrategy.withdraw.selector, assets, receiver, owner, maxLoss)
            ),
            (uint256)
        );
        _postWithdrawHook(assets, shares, receiver, owner, maxLoss);
    }

    /**
     * @notice Redeem shares for assets
     * @param shares Amount of shares to redeem
     * @param receiver Address to receive the assets
     * @param owner Address whose shares are burned
     * @return assets Amount of assets withdrawn
     */
    function redeem(uint256 shares, address receiver, address owner) external virtual returns (uint256 assets) {
        return redeem(shares, receiver, owner, MAX_BPS);
    }

    /**
     * @notice Redeem shares with custom max loss
     * @param shares Amount of shares to redeem
     * @param receiver Address to receive the assets
     * @param owner Address whose shares are burned
     * @param maxLoss Maximum acceptable loss in basis points
     * @return assets Amount of assets withdrawn
     */
    function redeem(uint256 shares, address receiver, address owner, uint256 maxLoss)
        public
        virtual
        returns (uint256 assets)
    {
        _preWithdrawHook(assets, shares, receiver, owner, maxLoss);
        assets = abi.decode(
            _delegateCall(abi.encodeWithSelector(ITokenizedStrategy.redeem.selector, shares, receiver, owner, maxLoss)),
            (uint256)
        );
        _postWithdrawHook(assets, shares, receiver, owner, maxLoss);
    }

    /**
     * @notice Transfer shares to another address
     * @param to Address to receive the shares
     * @param amount Amount of shares to transfer
     * @return success Whether the transfer succeeded
     */
    function transfer(address to, uint256 amount) external virtual returns (bool) {
        _preTransferHook(msg.sender, to, amount);
        bool success =
            abi.decode(_delegateCall(abi.encodeCall(ITokenizedStrategy(address(this)).transfer, (to, amount))), (bool));
        _postTransferHook(msg.sender, to, amount, success);
        return success;
    }

    /**
     * @notice Transfer shares from one address to another
     * @param from Address to transfer from
     * @param to Address to transfer to
     * @param amount Amount of shares to transfer
     * @return success Whether the transfer succeeded
     */
    function transferFrom(address from, address to, uint256 amount) external virtual returns (bool) {
        _preTransferHook(from, to, amount);
        bool success = abi.decode(
            _delegateCall(abi.encodeCall(ITokenizedStrategy(address(this)).transferFrom, (from, to, amount))), (bool)
        );
        _postTransferHook(from, to, amount, success);
        return success;
    }

    /**
     * @notice Report profit and loss
     * @return profit Amount of profit generated
     * @return loss Amount of loss incurred
     */
    function report() external virtual returns (uint256 profit, uint256 loss) {
        _preReportHook();
        (profit, loss) =
            abi.decode(_delegateCall(abi.encodeCall(ITokenizedStrategy(address(this)).report, ())), (uint256, uint256));
        _postReportHook(profit, loss);
    }
}
"
    },
    "lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @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 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 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 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));
    }

    /**
     * @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 Set the calling contract's allowance toward `sp

Tags:
ERC20, Multisig, Mintable, Swap, Liquidity, Staking, Yield, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xbd35e3bd64eed7db85162bc2a4e4f37796247c2e|verified:true|block:23628210|tx:0xf2e6dc3ab876e61bdd686ccc21565b2865bc9d8c74524c4bdc07878fc2713109|first_check:1761228353

Submitted on: 2025-10-23 16:05:55

Comments

Log in to comment.

No comments yet.