Pendle Market V3

Pendle Market V3 is an AMM dex. Different from Uniswap V2’s constant product model, it is based on Notional model to provide better liquidity to users.
The trade pair is ST and PT, which provides market for traders to exchange ST and PT.

PendleMarketFactoryV3

createNewMarket function allows anyone to create market based on PT and corresponding ST permissionlessly.
scalarRoot and initialAnchor decides trading curve’s shape. lnFeeRateRoot decides the protocol fee charged.
/// --- pendle-core-v2-public/contracts/core/Market/v3/PendleMarketFactoryV3.sol --- /** * @notice Create a market between PT and its corresponding SY with scalar & anchor config. * Anyone is allowed to create a market on their own. */ function createNewMarket( address PT, int256 scalarRoot, int256 initialAnchor, uint80 lnFeeRateRoot ) external returns (address market) { if (!IPYieldContractFactory(yieldContractFactory).isPT(PT)) revert Errors.MarketFactoryInvalidPt(); if (IPPrincipalToken(PT).isExpired()) revert Errors.MarketFactoryExpiredPt(); if (lnFeeRateRoot > maxLnFeeRateRoot) revert Errors.MarketFactoryLnFeeRateRootTooHigh(lnFeeRateRoot, maxLnFeeRateRoot); if (markets[PT][scalarRoot][initialAnchor][lnFeeRateRoot] != address(0)) revert Errors.MarketFactoryMarketExists(); if (initialAnchor < minInitialAnchor) revert Errors.MarketFactoryInitialAnchorTooLow(initialAnchor, minInitialAnchor); market = BaseSplitCodeFactory._create2( 0, bytes32(block.chainid), abi.encode(PT, scalarRoot, initialAnchor, lnFeeRateRoot, vePendle, gaugeController), marketCreationCodeContractA, marketCreationCodeSizeA, marketCreationCodeContractB, marketCreationCodeSizeB ); markets[PT][scalarRoot][initialAnchor][lnFeeRateRoot] = market; if (!allMarkets.add(market)) assert(false); emit CreateNewMarket(market, PT, scalarRoot, initialAnchor, lnFeeRateRoot); }

PendleMarketV3

mint

mint function allows user to provider liquidity.
The logic of lp calculation is exactly same as Uniswap V2.
/// --- pendle-core-v2-public/contracts/core/Market/v3/PendleMarketV3.sol --- struct MarketState { int256 totalPt; // total amount of pt in pool int256 totalSy; // total amount of sy in pool int256 totalLp; // total lp amount address treasury; // treasury address /// immutable variables /// int256 scalarRoot; uint256 expiry; /// fee data /// uint256 lnFeeRateRoot; uint256 reserveFeePercent; // base 100 /// last trade data /// uint256 lastLnImpliedRate; } /** * @notice PendleMarket allows users to provide in PT & SY in exchange for LPs, which * will grant LP holders more exchange fee over time * @dev will mint as much LP as possible such that the corresponding SY and PT used do * not exceed `netSyDesired` and `netPtDesired`, respectively * @dev PT and SY should be transferred to this contract prior to calling * @dev will revert if PT is expired */ function mint( address receiver, uint256 netSyDesired, uint256 netPtDesired ) external nonReentrant notExpired returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed) { MarketState memory market = readState(msg.sender); PYIndex index = YT.newIndex(); uint256 lpToReserve; (lpToReserve, netLpOut, netSyUsed, netPtUsed) = market.addLiquidity( netSyDesired, netPtDesired, block.timestamp ); // initializing the market if (lpToReserve != 0) { market.setInitialLnImpliedRate(index, initialAnchor, block.timestamp); _mint(address(1), lpToReserve); } _mint(receiver, netLpOut); _writeState(market); if (_selfBalance(SY) < market.totalSy.Uint()) revert Errors.MarketInsufficientSyReceived(_selfBalance(SY), market.totalSy.Uint()); if (_selfBalance(PT) < market.totalPt.Uint()) revert Errors.MarketInsufficientPtReceived(_selfBalance(PT), market.totalPt.Uint()); emit Mint(receiver, netLpOut, netSyUsed, netPtUsed); } /** * @notice read the state of the market from storage into memory for gas-efficient manipulation */ function readState(address router) public view returns (MarketState memory market) { market.totalPt = _storage.totalPt; market.totalSy = _storage.totalSy; market.totalLp = totalSupply().Int(); uint80 overriddenFee; (market.treasury, overriddenFee, market.reserveFeePercent) = IPMarketFactoryV3(factory).getMarketConfig( address(this), router ); market.lnFeeRateRoot = overriddenFee == 0 ? lnFeeRateRoot : overriddenFee; market.scalarRoot = scalarRoot; market.expiry = expiry; market.lastLnImpliedRate = _storage.lastLnImpliedRate; }

addLiquidity

/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function addLiquidity( MarketState memory market, uint256 syDesired, uint256 ptDesired, uint256 blockTime ) internal pure returns (uint256 lpToReserve, uint256 lpToAccount, uint256 syUsed, uint256 ptUsed) { (int256 _lpToReserve, int256 _lpToAccount, int256 _syUsed, int256 _ptUsed) = addLiquidityCore( market, syDesired.Int(), ptDesired.Int(), blockTime ); lpToReserve = _lpToReserve.Uint(); lpToAccount = _lpToAccount.Uint(); syUsed = _syUsed.Uint(); ptUsed = _ptUsed.Uint(); }

addLiquidityCore

It is not allowed to add liquidity if the market has expired.
/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function addLiquidityCore( MarketState memory market, int256 syDesired, int256 ptDesired, uint256 blockTime ) internal pure returns (int256 lpToReserve, int256 lpToAccount, int256 syUsed, int256 ptUsed) { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (syDesired == 0 || ptDesired == 0) revert Errors.MarketZeroAmountsInput(); if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ if (market.totalLp == 0) { lpToAccount = PMath.sqrt((syDesired * ptDesired).Uint()).Int() - MINIMUM_LIQUIDITY; lpToReserve = MINIMUM_LIQUIDITY; syUsed = syDesired; ptUsed = ptDesired; } else { int256 netLpByPt = (ptDesired * market.totalLp) / market.totalPt; int256 netLpBySy = (syDesired * market.totalLp) / market.totalSy; if (netLpByPt < netLpBySy) { lpToAccount = netLpByPt; ptUsed = ptDesired; syUsed = (market.totalSy * lpToAccount).rawDivUp(market.totalLp); } else { lpToAccount = netLpBySy; syUsed = syDesired; ptUsed = (market.totalPt * lpToAccount).rawDivUp(market.totalLp); } } if (lpToAccount <= 0 || syUsed <= 0 || ptUsed <= 0) revert Errors.MarketZeroAmountsOutput(); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ market.totalSy += syUsed; market.totalPt += ptUsed; market.totalLp += lpToAccount + lpToReserve; }

_writeState

/// --- pendle-core-v2-public/contracts/core/Market/v3/PendleMarketV3.sol --- /// @notice write back the state of the market from memory to storage function _writeState(MarketState memory market) internal { uint96 lastLnImpliedRate96 = market.lastLnImpliedRate.Uint96(); int128 totalPt128 = market.totalPt.Int128(); int128 totalSy128 = market.totalSy.Int128(); (uint16 observationIndex, uint16 observationCardinality) = observations.write( _storage.observationIndex, uint32(block.timestamp), _storage.lastLnImpliedRate, _storage.observationCardinality, _storage.observationCardinalityNext ); _storage.totalPt = totalPt128; _storage.totalSy = totalSy128; _storage.lastLnImpliedRate = lastLnImpliedRate96; _storage.observationIndex = observationIndex; _storage.observationCardinality = observationCardinality; emit UpdateImpliedRate(block.timestamp, market.lastLnImpliedRate); }

setInitialLnImpliedRate

setInitialLnImpliedRate calcualtes current implied investment rate on PT (in one year) based on exchange rate between PT and ST.
/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function setInitialLnImpliedRate( MarketState memory market, PYIndex index, int256 initialAnchor, uint256 blockTime ) internal pure { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ int256 totalAsset = index.syToAsset(market.totalSy); uint256 timeToExpiry = market.expiry - blockTime; int256 rateScalar = _getRateScalar(market, timeToExpiry); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ market.lastLnImpliedRate = _getLnImpliedRate( market.totalPt, totalAsset, rateScalar, initialAnchor, timeToExpiry ); }

_getRateScalar

/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function _getRateScalar(MarketState memory market, uint256 timeToExpiry) internal pure returns (int256 rateScalar) { rateScalar = (market.scalarRoot * IMPLIED_RATE_TIME.Int()) / timeToExpiry.Int(); if (rateScalar <= 0) revert Errors.MarketRateScalarBelowZero(rateScalar); }

_getLnImpliedRate

/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- /// @notice Calculates the current market implied rate. /// @return lnImpliedRate the implied rate function _getLnImpliedRate( int256 totalPt, int256 totalAsset, int256 rateScalar, int256 rateAnchor, uint256 timeToExpiry ) internal pure returns (uint256 lnImpliedRate) { // This will check for exchange rates < PMath.IONE int256 exchangeRate = _getExchangeRate(totalPt, totalAsset, rateScalar, rateAnchor, 0); // exchangeRate >= 1 so its ln >= 0 uint256 lnRate = exchangeRate.ln().Uint(); lnImpliedRate = (lnRate * IMPLIED_RATE_TIME) / timeToExpiry; }

burn

/// --- pendle-core-v2-public/contracts/core/Market/v3/PendleMarketV3.sol --- /** * @notice LP Holders can burn their LP to receive back SY & PT proportionally * to their share of the market */ function burn( address receiverSy, address receiverPt, uint256 netLpToBurn ) external nonReentrant returns (uint256 netSyOut, uint256 netPtOut) { MarketState memory market = readState(msg.sender); _burn(address(this), netLpToBurn); (netSyOut, netPtOut) = market.removeLiquidity(netLpToBurn); if (receiverSy != address(this)) IERC20(SY).safeTransfer(receiverSy, netSyOut); if (receiverPt != address(this)) IERC20(PT).safeTransfer(receiverPt, netPtOut); _writeState(market); emit Burn(receiverSy, receiverPt, netLpToBurn, netSyOut, netPtOut); }

swapExactPtForSy

swapExactPtForSy function allows user to swap exact PT for SY.
/// --- pendle-core-v2-public/contracts/core/Market/v3/PendleMarketV3.sol --- /** * @notice Pendle Market allows swaps between PT & SY it is holding. This function * aims to swap an exact amount of PT to SY. * @dev steps working of this contract - The outcome amount of SY will be precomputed by MarketMathLib - Release the calculated amount of SY to receiver - Callback to msg.sender if data.length > 0 - Ensure exactPtIn amount of PT has been transferred to this address * @dev will revert if PT is expired * @param data bytes data to be sent in the callback (if any) */ function swapExactPtForSy( address receiver, uint256 exactPtIn, bytes calldata data ) external nonReentrant notExpired returns (uint256 netSyOut, uint256 netSyFee) { MarketState memory market = readState(msg.sender); uint256 netSyToReserve; (netSyOut, netSyFee, netSyToReserve) = market.swapExactPtForSy(YT.newIndex(), exactPtIn, block.timestamp); if (receiver != address(this)) IERC20(SY).safeTransfer(receiver, netSyOut); IERC20(SY).safeTransfer(market.treasury, netSyToReserve); _writeState(market); if (data.length > 0) { IPMarketSwapCallback(msg.sender).swapCallback(exactPtIn.neg(), netSyOut.Int(), data); } if (_selfBalance(PT) < market.totalPt.Uint()) revert Errors.MarketInsufficientPtReceived(_selfBalance(PT), market.totalPt.Uint()); emit Swap(msg.sender, receiver, exactPtIn.neg(), netSyOut.Int(), netSyFee, netSyToReserve); } /// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function swapExactPtForSy( MarketState memory market, PYIndex index, uint256 exactPtToMarket, uint256 blockTime ) internal pure returns (uint256 netSyToAccount, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore( market, index, exactPtToMarket.neg(), blockTime ); netSyToAccount = _netSyToAccount.Uint(); netSyFee = _netSyFee.Uint(); netSyToReserve = _netSyToReserve.Uint(); }

executeTradeCore

/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function executeTradeCore( MarketState memory market, PYIndex index, int256 netPtToAccount, uint256 blockTime ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); if (market.totalPt <= netPtToAccount) revert Errors.MarketInsufficientPtForTrade(market.totalPt, netPtToAccount); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ MarketPreCompute memory comp = getMarketPreCompute(market, index, blockTime); (netSyToAccount, netSyFee, netSyToReserve) = calcTrade(market, comp, index, netPtToAccount); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ _setNewMarketStateTrade(market, comp, index, netPtToAccount, netSyToAccount, netSyToReserve, blockTime); }

swapSyForExactPt

swapSyForExactPt function allows users to swap SY for exact PT.
/// --- pendle-core-v2-public/contracts/core/Market/v3/PendleMarketV3.sol --- /** * @notice Pendle Market allows swaps between PT & SY it is holding. This function * aims to swap SY for an exact amount of PT. * @dev steps working of this function - The exact outcome amount of PT will be transferred to receiver - Callback to msg.sender if data.length > 0 - Ensure the calculated required amount of SY is transferred to this address * @dev will revert if PT is expired * @param data bytes data to be sent in the callback (if any) */ function swapSyForExactPt( address receiver, uint256 exactPtOut, bytes calldata data ) external nonReentrant notExpired returns (uint256 netSyIn, uint256 netSyFee) { MarketState memory market = readState(msg.sender); uint256 netSyToReserve; (netSyIn, netSyFee, netSyToReserve) = market.swapSyForExactPt(YT.newIndex(), exactPtOut, block.timestamp); if (receiver != address(this)) IERC20(PT).safeTransfer(receiver, exactPtOut); IERC20(SY).safeTransfer(market.treasury, netSyToReserve); _writeState(market); if (data.length > 0) { IPMarketSwapCallback(msg.sender).swapCallback(exactPtOut.Int(), netSyIn.neg(), data); } // have received enough SY if (_selfBalance(SY) < market.totalSy.Uint()) revert Errors.MarketInsufficientSyReceived(_selfBalance(SY), market.totalSy.Uint()); emit Swap(msg.sender, receiver, exactPtOut.Int(), netSyIn.neg(), netSyFee, netSyToReserve); } /// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- function swapSyForExactPt( MarketState memory market, PYIndex index, uint256 exactPtToAccount, uint256 blockTime ) internal pure returns (uint256 netSyToMarket, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore( market, index, exactPtToAccount.Int(), blockTime ); netSyToMarket = _netSyToAccount.neg().Uint(); netSyFee = _netSyFee.Uint(); netSyToReserve = _netSyToReserve.Uint(); }

Exchange Rate Calculation

_getExchangeRate

_getExchangeRate function returns exchange rate to apply in swap. Rather than using algorithm Δy = (y × Δx) / (x + Δx) in Uniswap, it uses a function of post-trade proportion to calculate exchange rate.
  • totalPt - netPtToAccount = PT balance AFTER the trade completes
  • totalPt + totalAsset = Total pool value BEFORE the trade
 
This algorithm is chosen because it operates under the assumption that the PT implied rate is relatively stable, which yields smoother exchanges and generally deeper liquidity.
notion image
notion image
 
For a more detailed explanation of this formula, please refer to Pendle’s whitepaper.
/// --- pendle-core-v2-public/contracts/core/Market/MarketMathCore.sol --- int256 internal constant MAX_MARKET_PROPORTION = (1e18 * 96) / 100; function _getExchangeRate( int256 totalPt, int256 totalAsset, int256 rateScalar, int256 rateAnchor, int256 netPtToAccount ) internal pure returns (int256 exchangeRate) { int256 numerator = totalPt.subNoNeg(netPtToAccount); int256 proportion = (numerator.divDown(totalPt + totalAsset)); if (proportion > MAX_MARKET_PROPORTION) revert Errors.MarketProportionTooHigh(proportion, MAX_MARKET_PROPORTION); int256 lnProportion = _logProportion(proportion); exchangeRate = lnProportion.divDown(rateScalar) + rateAnchor; if (exchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(exchangeRate); } function _logProportion(int256 proportion) internal pure returns (int256 res) { if (proportion == PMath.IONE) revert Errors.MarketProportionMustNotEqualOne(); int256 logitP = proportion.divDown(PMath.IONE - proportion); res = logitP.ln(); }