PendleV2FarmV3

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/integrations/farms/PendleV2FarmV3.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {FixedPointMathLib} from "@solmate/src/utils/FixedPointMathLib.sol";
import {IPPYLpOracle as IPendleOracle} from "@pendle/interfaces/IPPYLpOracle.sol";

import {CoreRoles} from "@libraries/CoreRoles.sol";
import {Accounting} from "@finance/Accounting.sol";
import {CoWSwapBase} from "@integrations/CoWSwapBase.sol";
import {IPendleV2FarmV3} from "@interfaces/IPendleV2FarmV3.sol";
import {MultiAssetFarmV2} from "@integrations/MultiAssetFarmV2.sol";
import {IMaturityFarm, IFarm} from "@interfaces/IMaturityFarm.sol";

import {PendleStructGen} from "@libraries/PendleStructGen.sol";
import {
    IPYieldToken,
    IPPrincipalToken,
    IStandardizedYield,
    IPAllActionV3,
    IPMarket
} from "@pendle/interfaces/IPAllActionV3.sol";

/// @title Pendle V2 Farm (V3)
/// @notice Integrates with Pendle v2 for yield token strategies
/// @dev This contract manages Principal Tokens (PTs) and provides yield interpolation mechanisms
/// @dev Inherits from MultiAssetFarm for multi-asset support and CoWSwapFarmBase for MEV protection
/// ## Yield Mechanism:
/// - Before maturity: PTs trade at discount, yield is interpolated linearly
/// - At maturity: PTs redeem 1:1 for yield tokens, creating yield spike
/// - Maturity discount factor accounts for potential swap losses
contract PendleV2FarmV3 is MultiAssetFarmV2, CoWSwapBase, ReentrancyGuard, IPendleV2FarmV3 {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;
    using FixedPointMathLib for uint256;

    IPYieldToken public immutable YT;
    IPPrincipalToken public immutable PT;
    IStandardizedYield public immutable SY;

    /// @notice Maturity timestamp of the Pendle market when PTs can be redeemed for underlying tokens
    uint256 public immutable maturity;

    /// @notice Reference to the Pendle market contract for this specific yield token
    IPMarket public immutable pendleMarket;

    /// @notice Reference to the Pendle oracle used for PT to underlying asset exchange rates
    address public immutable pendleOracle;

    /// @notice TWAP duration for Pendle oracle queries (30 minutes)
    uint32 private constant _PENDLE_ORACLE_TWAP_DURATION = 1800;

    /// @notice The underlying asset token that PTs will be 1-1 with at maturity
    /// @dev NOTE: Always make sure that pivot token is not rebasing
    address public immutable pivotToken;

    /// @notice Address of the Pendle router used for executing swaps and PT operations
    IPAllActionV3 public pendleRouter;

    /// @notice Address that receives PTs when transferred from this farm
    address public ptReceiver;

    /// @notice Total number of PTs currently held by this farm (tracked for reconciliation)
    uint256 public totalReceivedPTs;

    /// @notice Minimum PT balance difference required to trigger reconciliation
    /// @dev Used to handle airdrops, external transfers, or accounting discrepancies
    uint256 public ptThreshold;

    /// @notice Discount factor applied to PT values at maturity to account for swap slippage
    /// @dev Reduces reported yield during PT holding period and creates yield spike at unwrap
    uint256 public maturityPTDiscount;

    /// @notice Timestamp of the last accrual rate update for yield interpolation
    uint256 public lastCheckpointTimestamp;

    /// @notice Rate at which yield accrues per second, denominated in assetTokens
    uint256 public accrualRate;

    /// @notice Total amount of assets currently wrapped as PTs, in assetTokens
    uint256 public totalWrappedAssets;

    /// @notice Initializes the PendleV2FarmV3 contract
    /// @param _core Address of the InfiniFi core contract
    /// @param _assetToken Primary asset token for this farm (e.g., USDC)
    /// @param _pendleMarket Address of the Pendle market for the target yield token
    /// @param _pendleOracle Address of the Pendle oracle for PT pricing
    /// @param _accounting Address of the accounting contract for price conversions
    /// @param _pendleRouter Address of the Pendle router for executing swaps
    /// @param _settlementContract Address of the CoW Protocol settlement contract
    /// @param _vaultRelayer Address of the CoW Protocol vault relayer
    /// @dev Validates that the Pendle market is properly initialized and oracle is ready
    /// @dev Sets up supported asset tokens from the SY's tokensIn and tokensOut arrays
    constructor(
        address _core,
        address _assetToken,
        address _pendleMarket,
        address _pendleOracle,
        address _accounting,
        address _pendleRouter,
        address _settlementContract,
        address _vaultRelayer
    ) CoWSwapBase(_settlementContract, _vaultRelayer, true) MultiAssetFarmV2(_core, _assetToken, _accounting) {
        pendleOracle = _pendleOracle;
        pendleMarket = IPMarket(_pendleMarket);
        pendleRouter = IPAllActionV3(_pendleRouter);

        // read expiry
        maturity = pendleMarket.expiry();
        // read contracts and keep some immutable variables to save gas
        (SY, PT, YT) = pendleMarket.readTokens();
        (, pivotToken,) = SY.assetInfo();

        address[] memory tokensIn = SY.getTokensIn();
        address[] memory tokensOut = SY.getTokensOut();

        _enableAsset(_assetToken);
        _enableAsset(pivotToken);

        for (uint256 i = 0; i < tokensIn.length; i++) {
            _enableAsset(tokensIn[i]);
        }

        for (uint256 i = 0; i < tokensOut.length; i++) {
            _enableAsset(tokensOut[i]);
        }

        // set default threshold 10 PTs
        ptThreshold = 10 * 10 ** (PT.decimals());
        // set default slippage tolerance to 0.3%
        maxSlippage = 0.997e18;
        // set default maturity discounting to 0.2%
        maturityPTDiscount = 0.998e18;

        // ensure pendle oracle is initialized for this market
        // https://docs.pendle.finance/Developers/Oracles/HowToIntegratePtAndLpOracle
        // this call will revert if the oracle is not initialized or if the cardinality
        // of the oracle has to be increased (if so, any eoa can do it on the Pendle contract
        // directly prior to deploying this farm).
        IPendleOracle(pendleOracle).getPtToAssetRate(_pendleMarket, _PENDLE_ORACLE_TWAP_DURATION);
    }

    /// @notice Ensures the farm's PT balance is reconciled before executing operations
    /// @dev Prevents operations when there's a significant discrepancy between tracked and actual PT balances
    /// @dev Allows small differences up to ptThreshold to account for rounding errors
    modifier onlyReconciled() {
        _checkIsReconciled();
        _;
    }

    /// @notice Updates the Pendle router address used for swaps
    /// @param _pendleRouter New address of the Pendle router
    /// @dev Only callable by PROTOCOL_PARAMETERS role
    function setPendleRouter(address _pendleRouter) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {
        pendleRouter = IPAllActionV3(_pendleRouter);
        emit PendleRouterUpdated(block.timestamp, _pendleRouter);
    }

    /// @notice Sets the discount factor applied to PT values at maturity
    /// @param _maturityPTDiscount New discount factor (1e18 = 100%, 0.998e18 = 99.8%)
    /// @dev WARNING: Changing this on a farm with invested PTs will cause a jump in reported assets()
    /// @dev Only callable by PROTOCOL_PARAMETERS role
    function setMaturityPTDiscount(uint256 _maturityPTDiscount) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {
        maturityPTDiscount = _maturityPTDiscount;
        _handleBalanceChange(0);
        emit MaturityPTDiscountUpdated(block.timestamp, _maturityPTDiscount);
    }

    /// @notice Sets the threshold for PT reconciliation
    /// @param _ptThreshold New threshold
    /// @dev Only callable by PROTOCOL_PARAMETERS role
    function setPtThreshold(uint256 _ptThreshold) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {
        ptThreshold = _ptThreshold;
        emit PTThresholdUpdated(block.timestamp, _ptThreshold);
    }

    /// @notice Sets the address that will receive PTs when transferred from this farm
    /// @param _ptReceiver Address to receive transferred PTs
    /// @dev Cannot be set to this contract's address
    /// @dev Only callable by PROTOCOL_PARAMETERS role
    function setPTReceiver(address _ptReceiver) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {
        require(_ptReceiver != address(this), PTReceiverIsSelf());
        ptReceiver = _ptReceiver;
        emit PTReceiverChanged(block.timestamp, _ptReceiver);
    }

    function assets() public view override returns (uint256) {
        uint256 supportedAssetBalance = MultiAssetFarmV2.assets();
        uint256 ptAssetsValue = ptToAssetsAtMaturity(totalReceivedPTs).mulWadDown(maturityPTDiscount) - remainingYield();

        return supportedAssetBalance + ptAssetsValue;
    }

    /// @notice Calculates the remaining yield that will be distributed until maturity
    /// @return Amount of yield remaining to be distributed, in assetTokens
    /// @dev Returns 0 if maturity has already passed
    function remainingYield() public view returns (uint256) {
        if (block.timestamp >= maturity) return 0;
        return accrualRate.mulWadDown(maturity - block.timestamp);
    }

    /// @notice Calculates the interpolated yield that is already reported by the farm
    /// @dev Returns 0 if maturity has already passed
    function interpolatedYield() public view returns (uint256) {
        if (block.timestamp >= maturity) return 0;
        if (block.timestamp <= lastCheckpointTimestamp) return 0;
        return accrualRate.mulWadUp(block.timestamp - lastCheckpointTimestamp);
    }

    /// ============================================================
    /// Wrap/Unwrap supported tokens to PTs
    /// ============================================================

    /// @notice Wraps supported tokens into Pendle Principal Tokens (PTs)
    /// @param _tokenIn Token to wrap (must be valid input for the SY)
    /// @param _amountIn Amount of tokens to wrap
    /// @dev Uses Pendle router to swap tokens for PTs with slippage protection
    /// @dev Can be called multiple times with partial amounts to reduce slippage
    /// @dev Transaction can be submitted privately to avoid MEV attacks
    /// @dev Only callable before maturity and by FARM_SWAP_CALLER role
    function wrapToPt(address _tokenIn, uint256 _amountIn)
        external
        whenNotPaused
        nonReentrant
        onlyReconciled
        onlyCoreRole(CoreRoles.FARM_SWAP_CALLER)
    {
        _validateAmount(_tokenIn, _amountIn);
        require(block.timestamp < maturity, PTAlreadyMatured(maturity));
        require(isAssetSupported(_tokenIn) && SY.isValidTokenIn(_tokenIn), InvalidToken(_tokenIn));

        // do swap
        IERC20(_tokenIn).forceApprove(address(pendleRouter), _amountIn);
        (uint256 ptReceived,,) = pendleRouter.swapExactTokenForPt(
            address(this),
            address(pendleMarket),
            0,
            PendleStructGen.createDefaultApprox(),
            PendleStructGen.createTokenInputStruct(_tokenIn, _amountIn),
            PendleStructGen.createEmptyLimitOrder()
        );

        _checkSlippageIn(_tokenIn, _amountIn, ptReceived);

        uint256 assetAmountIn = convert(_tokenIn, assetToken, _amountIn);
        _handleBalanceChange(int256(assetAmountIn));

        emit PTWrapped(block.timestamp, _tokenIn, _amountIn, ptReceived, assetAmountIn);
    }

    /// @notice Unwraps Pendle Principal Tokens (PTs) into supported tokens
    /// @param _tokenOut Token to receive (must be valid output for the SY)
    /// @param _ptTokensIn Amount of PTs to unwrap
    /// @dev Uses Pendle router to swap PTs for tokens with slippage protection
    /// @dev Before maturity: swaps PTs for tokens on the market
    /// @dev After maturity: redeems PTs directly for supported out tokens
    /// @dev MANUAL_REBALANCER role can unwrap before maturity for emergency exits
    /// @dev Only callable by FARM_SWAP_CALLER role
    function unwrapFromPt(address _tokenOut, uint256 _ptTokensIn)
        external
        whenNotPaused
        nonReentrant
        onlyReconciled
        onlyCoreRole(CoreRoles.FARM_SWAP_CALLER)
    {
        _validateAmount(address(PT), _ptTokensIn);
        require(isAssetSupported(_tokenOut) && SY.isValidTokenOut(_tokenOut), InvalidToken(_tokenOut));

        // MANUAL_REBALANCER role can bypass the maturity check and manually
        // exit positions before maturity.
        if (!core().hasRole(CoreRoles.MANUAL_REBALANCER, msg.sender)) {
            require(block.timestamp >= maturity, PTNotMatured(maturity));
        }

        uint256 tokensOut = 0;
        // do swap
        IERC20(PT).forceApprove(address(pendleRouter), _ptTokensIn);
        if (block.timestamp < maturity) {
            (tokensOut,,) = pendleRouter.swapExactPtForToken(
                address(this),
                address(pendleMarket),
                _ptTokensIn,
                PendleStructGen.createTokenOutputStruct(_tokenOut, 0),
                PendleStructGen.createEmptyLimitOrder()
            );
        } else {
            (tokensOut,) = pendleRouter.redeemPyToToken(
                address(this), address(YT), _ptTokensIn, PendleStructGen.createTokenOutputStruct(_tokenOut, 0)
            );
        }

        _checkSlippageOut(_tokenOut, _ptTokensIn, tokensOut);

        uint256 assetsOut = convert(_tokenOut, assetToken, tokensOut);
        _handleBalanceChange(-int256(assetsOut));

        emit PTUnwrapped(block.timestamp, _tokenOut, _ptTokensIn, tokensOut, assetsOut);
    }

    /// @notice Wraps tokens into PTs using custom Pendle router calldata
    /// @param _tokenIn Token to wrap (must be supported by the farm)
    /// @param _amountIn Amount of tokens to wrap
    /// @param _calldata Custom calldata for Pendle router execution
    /// @dev Allows for custom swap parameters and advanced Pendle operations
    /// @dev Can be called multiple times with partial amounts to reduce slippage
    /// @dev Transaction can be submitted privately to avoid MEV attacks
    /// @dev Only callable before maturity and by FARM_SWAP_CALLER role
    function wrapToPt(address _tokenIn, uint256 _amountIn, bytes memory _calldata)
        external
        whenNotPaused
        nonReentrant
        onlyReconciled
        onlyCoreRole(CoreRoles.FARM_SWAP_CALLER)
    {
        _validateAmount(_tokenIn, _amountIn);
        require(block.timestamp < maturity, PTAlreadyMatured(maturity));
        require(isAssetSupported(_tokenIn), InvalidToken(_tokenIn));

        uint256 ptBalanceBefore = PT.balanceOf(address(this));

        // do swap
        IERC20(_tokenIn).forceApprove(address(pendleRouter), _amountIn);
        (bool success, bytes memory reason) = address(pendleRouter).call(_calldata);
        require(success, SwapFailed(reason));

        // check slippage
        uint256 ptBalanceAfter = PT.balanceOf(address(this));
        uint256 ptReceived = ptBalanceAfter - ptBalanceBefore;

        _checkSlippageIn(_tokenIn, _amountIn, ptReceived);

        // tokens are returned from SY getTokensOut
        uint256 assetAmountIn = convert(_tokenIn, assetToken, _amountIn);
        _handleBalanceChange(int256(assetAmountIn));

        emit PTZappedIn(block.timestamp, _tokenIn, _amountIn, ptReceived, assetAmountIn);
    }

    /// @notice Unwraps PTs into tokens using custom Pendle router calldata
    /// @param _tokenOut Token to receive (must be supported by the farm)
    /// @param _ptTokensIn Amount of PTs to unwrap
    /// @param _calldata Custom calldata for Pendle router execution
    /// @dev Allows for custom swap parameters and advanced Pendle operations
    /// @dev MANUAL_REBALANCER role can unwrap before maturity for emergency exits
    /// @dev Only callable by FARM_SWAP_CALLER role
    function unwrapFromPt(address _tokenOut, uint256 _ptTokensIn, bytes memory _calldata)
        external
        whenNotPaused
        nonReentrant
        onlyReconciled
        onlyCoreRole(CoreRoles.FARM_SWAP_CALLER)
    {
        _validateAmount(address(PT), _ptTokensIn);
        require(isAssetSupported(_tokenOut), InvalidToken(_tokenOut));
        // MANUAL_REBALANCER role can bypass the maturity check and manually
        // exit positions before maturity.
        if (!core().hasRole(CoreRoles.MANUAL_REBALANCER, msg.sender)) {
            require(block.timestamp >= maturity, PTNotMatured(maturity));
        }

        uint256 tokensBefore = IERC20(_tokenOut).balanceOf(address(this));

        // do swap
        IERC20(PT).forceApprove(address(pendleRouter), _ptTokensIn);
        (bool success, bytes memory reason) = address(pendleRouter).call(_calldata);
        require(success, SwapFailed(reason));

        // check slippage
        uint256 tokensAfter = IERC20(_tokenOut).balanceOf(address(this));
        uint256 tokensOut = tokensAfter - tokensBefore;

        _checkSlippageOut(_tokenOut, _ptTokensIn, tokensOut);

        uint256 assetsOut = convert(_tokenOut, assetToken, tokensOut);
        _handleBalanceChange(-int256(assetsOut));

        emit PTZappedOut(block.timestamp, _tokenOut, tokensOut, _ptTokensIn, assetsOut);
    }

    /// @notice Transfers PTs to the configured receiver and reconciles accounting
    /// @param _amount Amount of PTs to transfer
    /// @dev HIGHLY SENSITIVE: Transfers PTs and updates accounting on both farms
    /// @dev Requires ptReceiver to be set and implements reconciliation
    /// @dev Only callable by FARM_SWAP_CALLER role
    function transferPt(uint256 _amount, bool _reconcile)
        external
        whenNotPaused
        onlyReconciled
        onlyCoreRole(CoreRoles.FARM_SWAP_CALLER)
    {
        _validateAmount(address(PT), _amount);
        require(ptReceiver != address(0), PTReceiverNotSet());

        IERC20(PT).safeTransfer(ptReceiver, _amount);

        int256 assetsValue = _estimateAssetsValue(-int256(_amount));
        _handleBalanceChange(assetsValue);

        if (_reconcile) {
            PendleV2FarmV3(ptReceiver).reconcilePt();
        }

        emit PTTransferred(block.timestamp, ptReceiver, _amount, uint256(-assetsValue));
    }

    /// @notice Reconciles tracked balances with actual token balances
    /// @dev This function should be called to handle PT airdrops, external transfers, or any
    /// scenario where the actual PT balance differs from the tracked balance.
    function reconcilePt() external whenNotPaused nonReentrant {
        uint256 balanceOfPTs = PT.balanceOf(address(this));
        int256 ptDifference = int256(balanceOfPTs) - int256(totalReceivedPTs);

        uint256 ptDifferenceAbs = uint256(ptDifference > 0 ? ptDifference : -ptDifference);
        require(ptDifferenceAbs >= ptThreshold, NoPTsToReconcile(ptDifference));

        int256 assetsValue = _estimateAssetsValue(ptDifference);
        _handleBalanceChange(assetsValue);

        emit PTReconciled(block.timestamp, assetsValue, ptDifference);
    }

    /// @notice Signs a CoW Protocol swap order for supported asset tokens
    /// @param _tokenIn Token to swap from
    /// @param _tokenOut Token to swap to
    /// @param _amountIn Amount of input token to swap
    /// @param _minAmountOut Minimum amount of output token expected
    /// @return Calldata for the CoW Protocol swap order
    /// @dev Both tokens must be supported and have oracles
    /// @dev Only callable by FARM_SWAP_CALLER role
    function signSwapOrder(address _tokenIn, address _tokenOut, uint256 _amountIn, uint256 _minAmountOut)
        external
        whenNotPaused
        onlyCoreRole(CoreRoles.FARM_SWAP_CALLER)
        returns (bytes memory)
    {
        _validateAmount(_tokenIn, _amountIn);
        CoWSwapBase.CoWSwapData memory _data =
            CoWSwapBase.CoWSwapData(_tokenIn, _tokenOut, _amountIn, _minAmountOut, maxSlippage);

        return _checkSwapApproveAndSignOrder(_data);
    }

    /// ============================================================
    /// PT Conversions to asset tokens
    /// ============================================================

    /// @notice Converts PTs to assetTokens using Pendle oracle rates
    /// @param _ptAmount Amount of PTs to convert
    /// @return Equivalent amount in assetTokens
    /// @dev Uses Pendle oracle TWAP for spot pricing
    /// @dev Returns 0 if oracle rate is unavailable
    function ptToAssets(uint256 _ptAmount) public view returns (uint256) {
        if (_ptAmount == 0) return 0;

        uint256 ptToSyAssetTokenRate =
            IPendleOracle(pendleOracle).getPtToAssetRate(address(pendleMarket), _PENDLE_ORACLE_TWAP_DURATION);

        if (ptToSyAssetTokenRate == 0) return 0;
        uint256 syAssetTokenAmount = _ptAmount.mulWadDown(ptToSyAssetTokenRate);
        return convert(pivotToken, assetToken, syAssetTokenAmount);
    }

    /// @notice Calculates the asset value of a given amount of PTs, at maturity
    /// @param _ptAmount Amount of PTs to value
    /// @return PT value in assetTokens
    /// @dev At maturity, PTs have a 1:1 conversion with pivot token, and PT token has the
    /// same amount of decimals as the pivot token, therefore we can do a conversion from
    /// pivot token to asset token to price the PTs at maturity.
    /// @dev this returns a raw value where maturityPTDiscount is not applied
    function ptToAssetsAtMaturity(uint256 _ptAmount) public view returns (uint256) {
        return convert(pivotToken, assetToken, _ptAmount);
    }

    /// ============================================================
    /// Internal functions
    /// ============================================================

    /// @notice Updates farm accounting when PT balance changes
    /// @param _assetsIn Change in assets (positive for deposits, negative for withdrawals)
    /// @dev Updates accrual rate and interpolation parameters for yield distribution
    /// @dev Clears accrual data after maturity as no more yield can be earned
    function _handleBalanceChange(int256 _assetsIn) internal {
        uint256 ptBalance = PT.balanceOf(address(this));
        totalReceivedPTs = ptBalance;
        if (block.timestamp >= maturity) {
            delete accrualRate;
            delete totalWrappedAssets;
            return;
        }

        uint256 currentAssets = totalWrappedAssets + interpolatedYield();

        if (_assetsIn > 0) {
            currentAssets += uint256(_assetsIn);
        } else {
            currentAssets = _safeSubtract(currentAssets, uint256(-_assetsIn));
        }

        uint256 assetsAtMaturity = ptToAssetsAtMaturity(ptBalance).mulWadDown(maturityPTDiscount);
        uint256 yieldDifference = _safeSubtract(assetsAtMaturity, currentAssets);
        uint256 _accrualRate = yieldDifference.divWadUp(maturity - block.timestamp);

        accrualRate = _accrualRate;
        lastCheckpointTimestamp = block.timestamp;
        totalWrappedAssets = assetsAtMaturity - yieldDifference;
    }

    /// @notice estimates asset value based on the current exchange rate between:
    /// the PTs held and the assets reported by the farm
    function _estimateAssetsValue(int256 _ptAmount) internal view returns (int256) {
        if (block.timestamp >= maturity) return 0;

        // farm must have actived wrap to be able to give estimates
        require(totalWrappedAssets > 0, FarmNotUsed(totalReceivedPTs, totalWrappedAssets));
        require(totalReceivedPTs > 0, FarmNotUsed(totalReceivedPTs, totalWrappedAssets));

        uint256 currentAssets = totalWrappedAssets + interpolatedYield();
        uint256 assetsAtMaturity = ptToAssetsAtMaturity(totalReceivedPTs);
        uint256 currentRatio = currentAssets.divWadUp(assetsAtMaturity);

        if (_ptAmount > 0) {
            uint256 _assetAmount = uint256(_ptAmount).mulWadDown(currentRatio);
            return int256(convert(pivotToken, assetToken, _assetAmount));
        }

        uint256 assetAmount = uint256(-_ptAmount).mulWadDown(currentRatio);
        return -int256(convert(pivotToken, assetToken, assetAmount));
    }

    /// @inheritdoc CoWSwapBase
    function _validateSwap(CoWSwapData memory _data) internal virtual override {
        require(isAssetSupported(_data.tokenIn), InvalidToken(_data.tokenIn));
        require(isAssetSupported(_data.tokenOut), InvalidToken(_data.tokenOut));
        require(_data.tokenIn != _data.tokenOut, InvalidToken(_data.tokenOut));

        uint256 minOutSlippage = convert(_data.tokenIn, _data.tokenOut, _data.amountIn).mulWadDown(_data.maxSlippage);
        require(_data.minAmountOut > minOutSlippage, SlippageTooHigh(minOutSlippage, _data.minAmountOut));
    }

    /// @notice Validates slippage for unwrap operations
    /// @param _tokenOut Token received from unwrapping
    /// @param _amountIn Amount of PTs unwrapped
    /// @param _amountOut Amount of tokens received
    /// @dev Ensures actual output meets minimum slippage requirements
    function _checkSlippageOut(address _tokenOut, uint256 _amountIn, uint256 _amountOut) private view {
        uint256 minOut = ptToAssets(_amountIn).mulWadDown(maxSlippage);
        uint256 assetsOut = convert(_tokenOut, assetToken, _amountOut);
        require(assetsOut >= minOut, SlippageTooHigh(minOut, assetsOut));
    }

    /// @notice Validates slippage for wrap operations
    /// @param _tokenIn Token used for wrapping
    /// @param _amountIn Amount of tokens wrapped
    /// @param _amountOut Amount of PTs received
    /// @dev Ensures actual output meets minimum slippage requirements
    function _checkSlippageIn(address _tokenIn, uint256 _amountIn, uint256 _amountOut) private view {
        uint256 assetsOut = convert(_tokenIn, assetToken, _amountIn);
        uint256 minOut = assetsOut.mulWadDown(maxSlippage);
        uint256 actualOut = ptToAssets(_amountOut);
        require(actualOut >= minOut, SlippageTooHigh(minOut, actualOut));
    }

    /// @notice Validates that the specified amount is valid and available
    /// @param _asset Address of the token to check
    /// @param _amount Amount to validate
    /// @dev Ensures amount is positive and doesn't exceed the contract's balance
    function _validateAmount(address _asset, uint256 _amount) internal view {
        require(_amount > 0, InvalidAmountIn(_amount));
        uint256 balance = IERC20(_asset).balanceOf(address(this));
        require(_amount <= balance, InsufficientBalance(_asset, _amount));
    }

    /// @notice Ensures the farm's PT balance is reconciled before executing operations
    /// @dev Prevents operations when there's a significant discrepancy between tracked and actual PT balances
    /// @dev In case there were no deposits in the farm or no unwraps allows operations
    /// @dev Allows small differences up to ptThreshold to account for rounding errors
    function _checkIsReconciled() internal view {
        if (totalReceivedPTs == 0) return;

        uint256 balanceOfPTs = PT.balanceOf(address(this));
        if (balanceOfPTs != totalReceivedPTs) {
            int256 ptDifference = int256(balanceOfPTs) - int256(totalReceivedPTs);
            uint256 ptDifferenceAbs = uint256(ptDifference > 0 ? ptDifference : -ptDifference);
            require(ptDifferenceAbs <= ptThreshold, FarmNotReconciled(totalReceivedPTs, balanceOfPTs));
        }
    }

    /// @notice Safely subtracts two numbers, returning 0 if underflow would occur
    /// @param _a First number
    /// @param _b Second number to subtract
    /// @return Result of subtraction or 0 if underflow
    /// @dev Used for approximations where underflow is acceptable
    function _safeSubtract(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return _a > _b ? _a - _b : 0;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

import {Arrays} from "../Arrays.sol";

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
"
    },
    "lib/solmate/src/utils/FixedPointMathLib.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx :

Tags:
ERC20, ERC165, Multisig, Mintable, Burnable, Pausable, Swap, Liquidity, Yield, Voting, Timelock, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xd91edc64f7d1d344c5955ba0516122ce8111bdb8|verified:true|block:23726398|tx:0x7a220399706de47ee7cc376ac294bbe8fcbb97919ce0ac2abea0aa8ffde7929d|first_check:1762268280

Submitted on: 2025-11-04 15:58:03

Comments

Log in to comment.

No comments yet.