USD3

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/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;
}
"
    },
    "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 `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);
        }
    }

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

    /**
     * @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 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));
    }
}
"
    },
    "lib/openzeppelin/contracts/utils/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.p

Tags:
ERC20, Multisig, Mintable, Swap, Liquidity, Staking, Yield, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x49ef4aef11d236a5e0879d07975fc30efd0df852|verified:true|block:23628201|tx:0x3fab40680318cd716c022bfd4caa1949bbc5cfe874782ef17e96d3e911389633|first_check:1761228265

Submitted on: 2025-10-23 16:04:27

Comments

Log in to comment.

No comments yet.