Verified contractPartialBUSL-1.1
AaveV4MoneyMarketView
Address0xba778e7075ac4dc19cd0be6a98f941052f404fa6
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,385,600
- Creation transaction
- 0x11b7474ead…4880ee7449
15 files
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/AaveV4MoneyMarketView.solmain6.98 KB
- lib/pendle-core-v2/contracts/core/libraries/math/LogExpMath.sol21.67 KB
- lib/pendle-core-v2/contracts/core/libraries/math/PMath.sol7.42 KB
- lib/pendle-core-v2/contracts/interfaces/IMoneyMarket.sol1.37 KB
- lib/pendle-core-v2/contracts/interfaces/IMoneyMarketView.sol1.43 KB
- lib/pendle-core-v2/contracts/interfaces/IPLoopPositionBox.sol1.78 KB
- lib/pendle-core-v2/contracts/interfaces/IPLoopPositionBoxFactory.sol1.34 KB
- lib/pendle-core-v2/contracts/interfaces/IPPTLooper.sol10.93 KB
- lib/pendle-core-v2/contracts/interfaces/IPPostPtLoopStateChecker.sol229 B
- lib/pendle-core-v2/contracts/pt-looping/money-market/BaseMoneyMarketView.sol4.55 KB
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/AaveV4MMPayloadLib.sol614 B
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/dependencies/IHubBase.sol3.26 KB
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/dependencies/ISpoke.sol4.6 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/AaveV4MoneyMarketView.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {IERC20Metadata as IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ISpoke} from "./dependencies/ISpoke.sol";
import {IHubBase} from "./dependencies/IHubBase.sol";
import {AaveV4MMPayloadLib} from "./AaveV4MMPayloadLib.sol";
import {BaseMoneyMarketView} from "../../BaseMoneyMarketView.sol";
import {IPLoopPositionBox, BoxData} from "../../../../interfaces/IPLoopPositionBox.sol";
import {PMath} from "../../../../core/libraries/math/PMath.sol";
contract AaveV4MoneyMarketView is BaseMoneyMarketView {
using PMath for uint256;
constructor(string memory _moneyMarketName, address _ptLooper) BaseMoneyMarketView(_moneyMarketName, _ptLooper) {}
/// @notice Aave V4 has one `collateralFactor` for both, so `ltv` is the liquidation line (HF == 1), not a
/// safe target. The caller's `postBorrowMaxLTV` must give the whole safety margin.
function _thresholds(IPLoopPositionBox box, BoxData memory bd)
internal
view
virtual
override
returns (uint256 ltv, uint256 liquidationThreshold)
{
(ISpoke spoke, uint256 collateralReserveId,) = AaveV4MMPayloadLib.unwrap(bd.mmPayload);
uint32 dynamicConfigKey = spoke.getUserPosition(collateralReserveId, box.SPOKE_MONEY_MARKET()).dynamicConfigKey;
ISpoke.DynamicReserveConfig memory dc = spoke.getDynamicReserveConfig(collateralReserveId, dynamicConfigKey);
ltv = liquidationThreshold = _bpsToWad(dc.collateralFactor);
}
/// @notice Known limitation: `borrowing` includes Hub cash and the spoke's `drawCap`, but not the spoke-wide
/// premium limit of `Hub._applyPremiumDelta`. A borrow within `borrowing` can still revert when the spoke is
/// at that limit and the box's collateral has a high `collateralRisk`.
function _liquidity(IPLoopPositionBox, BoxData memory bd)
internal
view
virtual
override
returns (uint256 borrowing, uint256 lending)
{
(ISpoke spoke, uint256 collateralReserveId, uint256 debtReserveId) = AaveV4MMPayloadLib.unwrap(bd.mmPayload);
// Lending
{
ISpoke.Reserve memory collReserve = spoke.getReserve(collateralReserveId);
IHubBase.SpokeData memory sd = collReserve.hub.getSpoke(collReserve.assetId, address(spoke));
if (sd.addCap == type(uint40).max) {
lending = IERC20(collReserve.underlying).totalSupply(); // No supply cap
} else {
uint256 capAssets = uint256(sd.addCap) * 10 ** collReserve.decimals;
uint256 currentAssets = collReserve.hub.previewRemoveByShares(collReserve.assetId, sd.addedShares);
lending = capAssets.subMax0(currentAssets);
}
}
// Borrowing
{
ISpoke.Reserve memory reserve = spoke.getReserve(debtReserveId);
IHubBase hub = reserve.hub;
IHubBase.SpokeData memory sd = hub.getSpoke(reserve.assetId, address(spoke));
uint256 hubLiquidity = hub.getAsset(reserve.assetId).liquidity;
if (sd.drawCap == type(uint40).max) {
borrowing = hubLiquidity;
} else {
uint256 capAssets = uint256(sd.drawCap) * 10 ** reserve.decimals;
// owed = drawnShares * drawnIndex + premium + deficit; `getSpokeTotalOwed` is all but the deficit.
// https://github.com/aave/aave-v4/blob/2524fe4018a42750300e114f2a8c4355df62a878/src/hub/libraries/AssetLogic.sol#L229
uint256 owedAssets = hub.getSpokeTotalOwed(reserve.assetId, address(spoke)) + _trimRay(sd.deficitRay);
uint256 capHeadroom = capAssets.subMax0(owedAssets);
borrowing = PMath.min(hubLiquidity, capHeadroom);
}
}
}
/// @dev `borrowing` is for this box: it includes the box's risk premium (`getUserLastRiskPremium`).
/// `lending` is market-wide: it includes the premium of all borrowers. See `_lendingApy`.
function _rates(IPLoopPositionBox box, BoxData memory bd)
internal
view
virtual
override
returns (uint256 borrowing, uint256 lending)
{
(ISpoke spoke, uint256 collateralReserveId, uint256 debtReserveId) = AaveV4MMPayloadLib.unwrap(bd.mmPayload);
uint256 boxRiskPremiumBps = spoke.getUserLastRiskPremium(box.SPOKE_MONEY_MARKET());
borrowing = _borrowApyWithPremium(spoke.getReserve(debtReserveId), boxRiskPremiumBps);
lending = _lendingApy(spoke.getReserve(collateralReserveId));
}
function _borrowApyWithPremium(ISpoke.Reserve memory reserve, uint256 riskPremiumBps)
internal
view
returns (uint256)
{
return _aaveV4Apy(_drawnRateWad(reserve).tweakUp(_bpsToWad(riskPremiumBps)));
}
/// @dev APY of `drawnRate * interestBearing / totalValue * (1 - liquidityFee)`.
function _lendingApy(ISpoke.Reserve memory reserve) internal view returns (uint256) {
// `totalValue` is the suppliers' whole claim, read directly (no shares rounding):
// https://github.com/aave/aave-v4/blob/2524fe4018a42750300e114f2a8c4355df62a878/src/hub/libraries/AssetLogic.sol#L79-L96
IHubBase.Asset memory collAsset = reserve.hub.getAsset(reserve.assetId);
uint256 totalValue = reserve.hub.getAddedAssets(reserve.assetId);
if (totalValue == 0) return 0;
// The principal that `drawnRate` accrues on: (drawnShares + premiumShares) * drawnIndex.
uint256 interestBearingShares = uint256(collAsset.drawnShares) + collAsset.premiumShares;
uint256 interestBearing = reserve.hub.previewRestoreByShares(reserve.assetId, interestBearingShares);
uint256 drawnRate = _drawnRateWad(reserve);
uint256 usageRatio = interestBearing.divDown(totalValue);
uint256 supplyApr = drawnRate.mulDown(usageRatio).tweakDown(_bpsToWad(collAsset.liquidityFee));
return _aaveV4Apy(supplyApr);
}
function _drawnRateWad(ISpoke.Reserve memory reserve) internal view returns (uint256) {
return _rayToWad(reserve.hub.getAssetDrawnRate(reserve.assetId));
}
// ========== Internal helpers ==========
/// @dev Compounds daily, like every other money market, so the APYs compare. Aave V4 compounds on each Hub
/// interaction, so this differs from Aave's own figure (about 0.01pp at normal rates).
function _aaveV4Apy(uint256 rate) internal pure returns (uint256) {
return _apy({rate: rate, perSeconds: 365 days});
}
function _bpsToWad(uint256 bps) internal pure returns (uint256) {
return bps * 1e14;
}
function _rayToWad(uint256 ray) internal pure returns (uint256) {
return ray / 1e9;
}
/// @dev RAY to a plain integer.
function _trimRay(uint256 ray) internal pure returns (uint256) {
return ray / 1e27;
}
}
lib/pendle-core-v2/contracts/core/libraries/math/LogExpMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation
// the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.8.0;
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128_000_000_000_000_000_000; // 2ˆ7
int256 constant a0 = 38_877_084_059_945_950_922_200_000_000_000_000_000_000_000_000_000_000_000; // eˆ(x0) (no
// decimals)
int256 constant x1 = 64_000_000_000_000_000_000; // 2ˆ6
int256 constant a1 = 6_235_149_080_811_616_882_910_000_000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3_200_000_000_000_000_000_000; // 2ˆ5
int256 constant a2 = 7_896_296_018_268_069_516_100_000_000_000_000; // eˆ(x2)
int256 constant x3 = 1_600_000_000_000_000_000_000; // 2ˆ4
int256 constant a3 = 888_611_052_050_787_263_676_000_000; // eˆ(x3)
int256 constant x4 = 800_000_000_000_000_000_000; // 2ˆ3
int256 constant a4 = 298_095_798_704_172_827_474_000; // eˆ(x4)
int256 constant x5 = 400_000_000_000_000_000_000; // 2ˆ2
int256 constant a5 = 5_459_815_003_314_423_907_810; // eˆ(x5)
int256 constant x6 = 200_000_000_000_000_000_000; // 2ˆ1
int256 constant a6 = 738_905_609_893_065_022_723; // eˆ(x6)
int256 constant x7 = 100_000_000_000_000_000_000; // 2ˆ0
int256 constant a7 = 271_828_182_845_904_523_536; // eˆ(x7)
int256 constant x8 = 50_000_000_000_000_000_000; // 2ˆ-1
int256 constant a8 = 164_872_127_070_012_814_685; // eˆ(x8)
int256 constant x9 = 25_000_000_000_000_000_000; // 2ˆ-2
int256 constant a9 = 128_402_541_668_774_148_407; // eˆ(x9)
int256 constant x10 = 12_500_000_000_000_000_000; // 2ˆ-3
int256 constant a10 = 113_314_845_306_682_631_683; // eˆ(x10)
int256 constant x11 = 6_250_000_000_000_000_000; // 2ˆ-4
int256 constant a11 = 106_449_445_891_785_942_956; // eˆ(x11)
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
unchecked {
require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "Invalid exponent");
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since
// it fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call
// x_n, where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal
// 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of
// this decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in
// the decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so
// deduct it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed
// point one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor
// series expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to
// multiply all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer
// multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
unchecked {
// The real natural logarithm is not defined for negative numbers or zero.
require(a > 0, "out of bounds");
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
}
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that r`esult. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
require(x < 2 ** 255, "x out of bounds");
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36.
// In both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit
// range.
require(y < MILD_EXPONENT_BOUND, "y out of bounds");
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't
// just bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, "product out of bounds"
);
return uint256(exp(logx_times_y));
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
unchecked {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive
// call. Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two,
// which we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n
// (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers
// cannot be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of
// this decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed
// point numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply
// them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so
// divide by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this
// format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor
// series that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder
// (both with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18
// decimal
// value.
return (sum + seriesSum) / 100;
}
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point
* argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
unchecked {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
}
lib/pendle-core-v2/contracts/core/libraries/math/PMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.8.0;
/* solhint-disable private-vars-leading-underscore, reason-string */
library PMath {
uint256 internal constant ONE = 1e18; // 18 decimal places
int256 internal constant IONE = 1e18; // 18 decimal places
function subMax0(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return (a >= b ? a - b : 0);
}
}
function subNoNeg(int256 a, int256 b) internal pure returns (int256) {
require(a >= b, "negative");
return a - b; // no unchecked since if b is very negative, a - b might overflow
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
unchecked {
return product / ONE;
}
}
function mulDown(int256 a, int256 b) internal pure returns (int256) {
int256 product = a * b;
unchecked {
return product / IONE;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 aInflated = a * ONE;
unchecked {
return aInflated / b;
}
}
function divDown(int256 a, int256 b) internal pure returns (int256) {
int256 aInflated = a * IONE;
unchecked {
return aInflated / b;
}
}
function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
function rawDivUp(int256 a, int256 b) internal pure returns (int256) {
return (a + b - 1) / b;
}
function tweakUp(uint256 a, uint256 factor) internal pure returns (uint256) {
return mulDown(a, ONE + factor);
}
function tweakDown(uint256 a, uint256 factor) internal pure returns (uint256) {
return mulDown(a, ONE - factor);
}
/// @return res = min(a + b, bound)
/// @dev This function should handle arithmetic operation and bound check without overflow/underflow
function addWithUpperBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) {
unchecked {
if (type(uint256).max - b < a) res = bound;
else res = min(bound, a + b);
}
}
/// @return res = max(a - b, bound)
/// @dev This function should handle arithmetic operation and bound check without overflow/underflow
function subWithLowerBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) {
unchecked {
if (b > a) res = bound;
else res = max(a - b, bound);
}
}
function clamp(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256 res) {
res = x;
if (x < lower) res = lower;
else if (x > upper) res = upper;
}
function clamp(int256 x, int256 lower, int256 upper) internal pure returns (int256 res) {
res = x;
if (x < lower) res = lower;
else if (x > upper) res = upper;
}
// @author Uniswap
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function square(uint256 x) internal pure returns (uint256) {
return x * x;
}
function squareDown(uint256 x) internal pure returns (uint256) {
return mulDown(x, x);
}
function abs(int256 x) internal pure returns (uint256) {
return uint256(x > 0 ? x : -x);
}
function neg(int256 x) internal pure returns (int256) {
return x * (-1);
}
function neg(uint256 x) internal pure returns (int256) {
return Int(x) * (-1);
}
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return (x > y ? x : y);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return (x > y ? x : y);
}
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return (x < y ? x : y);
}
function min(int256 x, int256 y) internal pure returns (int256) {
return (x < y ? x : y);
}
/*///////////////////////////////////////////////////////////////
SIGNED CASTS
//////////////////////////////////////////////////////////////*/
function Int(uint256 x) internal pure returns (int256) {
require(x <= uint256(type(int256).max));
return int256(x);
}
function Int128(int256 x) internal pure returns (int128) {
require(type(int128).min <= x && x <= type(int128).max);
return int128(x);
}
function Int128(uint256 x) internal pure returns (int128) {
return Int128(Int(x));
}
/*///////////////////////////////////////////////////////////////
UNSIGNED CASTS
//////////////////////////////////////////////////////////////*/
function Uint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function Uint32(uint256 x) internal pure returns (uint32) {
require(x <= type(uint32).max);
return uint32(x);
}
function Uint64(uint256 x) internal pure returns (uint64) {
require(x <= type(uint64).max);
return uint64(x);
}
function Uint112(uint256 x) internal pure returns (uint112) {
require(x <= type(uint112).max);
return uint112(x);
}
function Uint96(uint256 x) internal pure returns (uint96) {
require(x <= type(uint96).max);
return uint96(x);
}
function Uint128(uint256 x) internal pure returns (uint128) {
require(x <= type(uint128).max);
return uint128(x);
}
function Uint192(uint256 x) internal pure returns (uint192) {
require(x <= type(uint192).max);
return uint192(x);
}
function Uint80(uint256 x) internal pure returns (uint80) {
require(x <= type(uint80).max);
return uint80(x);
}
function Uint152(uint256 x) internal pure returns (uint152) {
require(x <= type(uint152).max);
return uint152(x);
}
function isAApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps);
}
function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
return a >= b && a <= mulDown(b, ONE + eps);
}
function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
return a <= b && a >= mulDown(b, ONE - eps);
}
}
lib/pendle-core-v2/contracts/interfaces/IMoneyMarket.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {IPLoopPositionBox, BoxData} from "./IPLoopPositionBox.sol";
/// @notice What every money market call acts on. Built from `BoxData` with `createMarketCtx`.
struct MarketCtx {
IPLoopPositionBox box;
bytes32 mmPayload;
address collateral;
address debtAsset;
}
function createMarketCtx(IPLoopPositionBox box, BoxData memory bd) pure returns (MarketCtx memory) {
return MarketCtx({box: box, mmPayload: bd.mmPayload, collateral: bd.spokePt, debtAsset: bd.spokeDebtToken});
}
interface IMoneyMarket {
function initialize(MarketCtx memory ctx) external;
function lend(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);
function withdraw(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);
function borrow(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);
function repay(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);
function collateralBalance(MarketCtx memory ctx) external returns (uint256 balance);
function debtBalance(MarketCtx memory ctx) external returns (uint256 balance);
/// @notice Oracle price of 1 PT wei in debt token wei, in WAD.
function oraclePtDebtRate(MarketCtx memory ctx) external view returns (uint256 rate);
}
lib/pendle-core-v2/contracts/interfaces/IMoneyMarketView.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {IPLoopPositionBox} from "./IPLoopPositionBox.sol";
struct Reward {
address token;
uint256 claimable;
}
struct Limits {
uint256 minBorrowing;
uint256 maxBorrowing;
uint256 minBorrowingForRewards;
uint256 minLending;
uint256 maxLending;
uint256 minLendingForRewards;
}
/// @dev Takes a box, not a `MarketCtx`, so off-chain callers need not build the ctx; the view reads
/// `BoxData` from the factory.
interface IMoneyMarketView {
function moneyMarketName() external view returns (string memory);
function moneyMarketBalances(IPLoopPositionBox box) external returns (uint256 mmPtBalance, uint256 mmDebtBalance);
function thresholds(IPLoopPositionBox box) external view returns (uint256 ltv, uint256 liquidationThreshold);
function liquidity(IPLoopPositionBox box) external view returns (uint256 borrowing, uint256 lending);
function rewards(IPLoopPositionBox box) external returns (Reward[] memory borrowing, Reward[] memory lending);
function limits(IPLoopPositionBox box) external view returns (Limits memory);
function rates(IPLoopPositionBox box) external view returns (uint256 borrowing, uint256 lending);
/// @notice Price of 1 PT wei in debt token wei, in WAD. Off-chain callers adjust for decimals.
function ptDebtRate(IPLoopPositionBox box) external view returns (uint256 rateWad);
}
lib/pendle-core-v2/contracts/interfaces/IPLoopPositionBox.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @dev `tokens` are ERC20 only; native value goes in `nativeAmount`. The other fields mirror `BoxApprovedCall`.
struct BoxCall {
address[] tokens;
uint256[] amounts;
uint256 nativeAmount;
address approve;
address extRouter;
bytes callData;
}
struct BoxData {
uint32 hubChainId;
uint32 spokeChainId;
address hubPt;
address hubDebtToken;
address spokePt;
address spokeDebtToken;
/// @dev Beacon of the spoke money market adapter.
address spokeMMBeacon;
/// @dev Adapter-specific market id. See each `*MMPayloadLib`.
bytes32 mmPayload;
}
interface IPLoopPositionBox {
function MANAGER() external view returns (address);
function OWNER() external view returns (address);
function BOX_ID() external view returns (bytes32);
function SPOKE_MONEY_MARKET() external view returns (address);
function initialize(
address owner,
bytes32 boxId,
address spokeMoneyMarket,
address ptToApprove,
address debtTokenToApprove
) external;
function withdrawTo(address to, address token, uint256 amount) external;
function approveAndCall(BoxCall memory call, address nativeRefund) external payable returns (bytes memory);
function MORPHO() external view returns (address);
/// @notice Manager only. Flash-borrows `assets` of `token` from Morpho and calls the manager with `data`
/// inside the loan. Morpho pulls the loan back after.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
/// @notice Morpho Blue flash-loan callback. Relays `data` to the manager.
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}
lib/pendle-core-v2/contracts/interfaces/IPLoopPositionBoxFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IMoneyMarket} from "./IMoneyMarket.sol";
import {BoxData, IPLoopPositionBox} from "./IPLoopPositionBox.sol";
interface IPLoopPositionBoxFactory {
event BoxDataRegistered(bytes32 indexed boxId, BoxData boxData);
function boxData(bytes32 boxId) external view returns (BoxData memory);
function computePositionBox(address owner, bytes32 boxId)
external
view
returns (address box, bytes32 salt, bool deployed);
/// @notice `computedAddr` is zero off the spoke chain.
function computeMoneyMarket(address owner, bytes32 boxId)
external
view
returns (address computedAddr, bytes32 salt, bool deployed);
/// @notice Deploys whichever is missing. `mm` is zero off the spoke chain.
function deployPositionBoxAndMoneyMarket(address owner, bytes32 boxId)
external
returns (IPLoopPositionBox box, IMoneyMarket mm, BoxData memory boxData);
function BEACON_PROXY_CODE_CONTRACT() external view returns (address);
function POSITION_BOX_BEACON() external view returns (address);
function POSITION_BOX_CODE_HASH() external view returns (bytes32);
// ========== Admin functions ==========
function registerBoxData(BoxData calldata boxData) external returns (bytes32 boxId);
}
lib/pendle-core-v2/contracts/interfaces/IPPTLooper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPLoopPositionBox} from "./IPLoopPositionBox.sol";
import {IPLoopPositionBoxFactory} from "./IPLoopPositionBoxFactory.sol";
import {IPPostPtLoopStateChecker} from "../interfaces/IPPostPtLoopStateChecker.sol";
/// @notice The owner approves a request (EIP-712, in the looper's domain). The executor builds a message for
/// each iteration, and the checker signs the whole `execute`. The box is `(ms.owner, req.header.boxId)`.
interface IPPTLooperEIP712Types {
/// @notice What the checker signs for `execute`. `calls` is hashed as an EIP-712 `bytes[]`.
struct Execution {
/// @notice The calls that `execute` runs in order, as delegatecalls into the looper.
bytes[] calls;
/// @notice The last timestamp at which `execute` can run.
uint256 deadline;
}
/// @notice A request runs iterations until it is terminated or expires. A box can have more than one
/// live request. `offchainMetadataHash` is `keccak256(offchainMetadata)`; the contract does not read it.
struct RequestHeader {
bytes32 boxId;
uint256 expiry;
uint256 swapBridgeSlippage;
bytes32 offchainMetadataHash;
}
struct BoxApprovedCall {
address extRouter;
address approve;
bytes callData;
}
/// @notice Cross-chain only. `maxAmount`: the max amount to bridge. `nativeFee`: the native fee of the call.
struct BridgeData {
BoxApprovedCall call;
uint256 maxAmount;
uint256 nativeFee;
}
struct IncreasePositionRequest {
RequestHeader header;
/// @notice The token that an iteration with `swapInitToken` swaps.
address initTokenIn;
/// @notice Min `netOut / netIn` (WAD) of an `initTokenIn` to PT swap. 0: no check.
uint256 initMinToPtSwapRate;
/// @notice Min `netOut / netIn` (WAD) of a debt token to PT swap. 0: no check.
uint256 minDebtToPtSwapRate;
/// @notice Max `debt / (collateral * oracle rate)` (WAD) after the iteration.
uint256 postBorrowMaxLTV;
/// @notice true: the swap mints PT + YT 1:1, and the YT goes to the owner.
bool isZeroPriceImpact;
}
struct IncreasePositionMessage {
address owner;
// Hub only.
/// @notice true: swap `req.initTokenIn` to PT. false: swap the debt token to PT. The fee is in the
/// token that is swapped.
bool swapInitToken;
/// @notice `extRouter == address(0)`: no swap.
BoxApprovedCall swap;
/// @notice Min `netOut / netIn` (WAD) of the swap; the higher of this and the request's rate applies.
uint256 minSwapRate;
uint256 fee;
// Cross-chain only: the hub bridges PT to the spoke; the spoke bridges debt back to the hub.
BridgeData bridge;
// Spoke only: lend, then borrow.
uint256 amountDebtBorrowed;
/// @notice Same-chain only. Debt token that the box flash-borrows from Morpho and pays back out of the
/// borrowed debt. 0: no flash loan.
uint256 flashAmount;
bytes postStateCheckData;
}
struct DecreasePositionRequest {
RequestHeader header;
/// @notice Min `netOut / netIn` (WAD) of a PT to debt token swap. 0: no check.
uint256 minPtToDebtSwapRate;
/// @notice Max `debt / (collateral * oracle rate)` (WAD) after the iteration.
uint256 postWithdrawMaxLTV;
/// @notice Hub only. true: the router redeems min(PT, YT) of the box 1:1 to the debt token. The rest
/// of the PT stays in the box. The owner sends the YT to the box first.
bool redeemWithPY;
}
struct DecreasePositionMessage {
address owner;
// Hub only: swap PT to the debt token.
/// @notice `extRouter == address(0)`: no swap. See `DecreasePositionRequest.redeemWithPY`.
BoxApprovedCall swap;
/// @notice Min `netOut / netIn` (WAD) of the swap; the higher of this and the request's rate applies.
uint256 minSwapRate;
// Cross-chain only: the hub bridges debt to the spoke; the spoke bridges PT back to the hub.
BridgeData bridge;
// Spoke only: repay, then withdraw.
uint256 amountPtWithdrawn;
/// @notice Hub only. In the debt token, out of the swap's output.
uint256 fee;
/// @notice Same-chain only. Debt token that the box flash-borrows from Morpho and pays back out of the
/// swap's output. 0: no flash loan.
uint256 flashAmount;
bytes postStateCheckData;
}
/// @notice Swaps the box's whole debt token balance on this chain to the token out, then sends it to the
/// owner, or bridges it when the destination is the other chain.
struct SwapBridgeWithdrawAllRequest {
RequestHeader header;
/// @notice true: the destination is the spoke. false: the hub.
bool receiveOnSpoke;
/// @notice The token out on the hub, when the iteration runs on the hub.
address hubTokenOut;
/// @notice The token out on the destination chain.
address dstTokenOut;
/// @notice Min box balance of the token out after the swap.
uint256 minTokenWithdrawn;
}
struct SwapBridgeWithdrawAllMessage {
address owner;
BoxApprovedCall swap;
/// @notice Min `netOut / netIn` (WAD) of the swap. 0: no check.
uint256 minSwapRate;
BridgeData bridge;
bytes postStateCheckData;
}
}
interface IPPTLooper is IPPTLooperEIP712Types {
/// @notice `DEFAULT`: cannot run. `APPROVED` (`approveRequest`): can run. `TERMINATED` (`terminateRequest`,
/// from any status): cannot run again. An iteration does not change the status.
enum RequestStatus {
DEFAULT,
APPROVED,
TERMINATED
}
event RequestApproved(address indexed owner, bytes32 requestHash);
event RequestTerminated(address indexed owner, bytes32 requestHash);
event SetExecutor(address executor);
event SetChecker(address checker);
event TokenSwapped(
IPLoopPositionBox indexed box,
address indexed tokenIn,
uint256 netIn,
address indexed tokenOut,
uint256 netSwappedOut
);
event PYRedeemed(
IPLoopPositionBox indexed box,
address indexed pt,
uint256 netPyIn,
address indexed tokenOut,
uint256 netSwappedOut
);
event TokenBridged(IPLoopPositionBox indexed box, address indexed token, uint256 amount);
/// @notice The `box` flash-borrowed `amount` of `token` for this iteration, repaid at the end.
/// `preDebtBalance` and `preInBalance` (when swapping the debt token) count the loan,
/// and so do the swap input and money market amounts. `postDebtBalance` does not include it.
event FlashLoaned(IPLoopPositionBox indexed box, address indexed token, uint256 amount);
/// @notice The money market adapter emits no events.
event MoneyMarketLentThenBorrowed(IPLoopPositionBox indexed box, uint256 ptLent, uint256 debtBorrowed);
/// @notice The money market adapter emits no events.
event MoneyMarketRepaidThenWithdrawn(IPLoopPositionBox indexed box, uint256 debtRepaid, uint256 ptWithdrawn);
event PositionIncreased(
address indexed owner,
bytes32 indexed boxId,
bytes32 requestHash,
/// @notice Hub only. The box's pre-fee balance of the token swapped (`initTokenIn` or the debt token).
uint256 preInBalance,
uint256 netPtToMM,
/// @notice Spoke only.
uint256 postDebtBalance
);
event PositionDecreased(
address indexed owner,
bytes32 indexed boxId,
bytes32 requestHash,
/// @notice Spoke only.
uint256 preDebtBalance,
uint256 netPtToSwap,
/// @notice Hub only. After the fee.
uint256 postDebtBalance
);
event Withdrawn(
address indexed owner, bytes32 indexed boxId, bytes32 requestHash, address tokenOut, uint256 netOut
);
// ========== Getters ==========
function POSITION_BOX_FACTORY() external view returns (IPLoopPositionBoxFactory);
function POST_LOOP_STATE_CHECKER() external view returns (IPPostPtLoopStateChecker);
function executor() external view returns (address);
function checker() external view returns (address);
function requestStatus(address owner, bytes32 requestHash) external view returns (RequestStatus);
// ========== Actions ==========
// Each action runs one iteration, executor only, inside `execute`. The request must be approved and not expired.
function increaseLoopPosition(IncreasePositionMessage memory ms, IncreasePositionRequest memory req) external;
function decreaseLoopPosition(DecreasePositionMessage memory ms, DecreasePositionRequest memory req) external;
function swapBridgeWithdrawAll(SwapBridgeWithdrawAllMessage memory ms, SwapBridgeWithdrawAllRequest memory req)
external;
/// @notice Approves a `DEFAULT` request. `requestHash` is the request's EIP-712 digest. The owner calls it,
/// or the executor calls it inside `execute` with the owner's signature of `requestHash`.
function approveRequest(address owner, bytes32 requestHash, bytes memory ownerSig) external;
/// @notice The request cannot run again. The owner calls it, or the executor inside `execute`.
function terminateRequest(address owner, bytes32 requestHash) external;
/// @notice Executor only, inside `execute`. Needs no request: funds go only to the owner or into the
/// owner's position. In order: `repayDebt` repays as much debt as the box's
/// debt token balance covers, `lendPt` lends its whole PT balance, then each token in `tokensToOwner`
/// goes to the owner in full.
/// `repayDebt` and `lendPt` need the spoke chain.
function settleBox(address owner, bytes32 boxId, bool repayDebt, bool lendPt, address[] calldata tokensToOwner)
external;
/// @notice The executor's only entry point. Runs `execution.calls` in order as delegatecalls into this
/// contract; any failure reverts all. With `tx.origin == 0` (an `eth_call` with no `from`) it is a
/// simulation: no checker signature or deadline.
/// @param execution the calls and the deadline.
/// @param checkerSig the checker's EIP-712 signature over `execution`.
/// @return results the return data of each call.
function execute(Execution memory execution, bytes calldata checkerSig) external returns (bytes[] memory results);
// ========== Admin functions ==========
function setExecutor(address executor) external;
function setChecker(address checker) external;
}
lib/pendle-core-v2/contracts/interfaces/IPPostPtLoopStateChecker.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.30;
import {MarketCtx} from "./IMoneyMarket.sol";
interface IPPostPtLoopStateChecker {
function check(MarketCtx memory ctx, bytes calldata data) external;
}
lib/pendle-core-v2/contracts/pt-looping/money-market/BaseMoneyMarketView.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {IPPTLooper} from "../../interfaces/IPPTLooper.sol";
import {IMoneyMarketView, Reward, Limits} from "../../interfaces/IMoneyMarketView.sol";
import {IMoneyMarket, MarketCtx, createMarketCtx} from "../../interfaces/IMoneyMarket.sol";
import {IPLoopPositionBoxFactory} from "../../interfaces/IPLoopPositionBoxFactory.sol";
import {IPLoopPositionBox, BoxData} from "../../interfaces/IPLoopPositionBox.sol";
import {LogExpMath} from "../../core/libraries/math/LogExpMath.sol";
import {PMath} from "../../core/libraries/math/PMath.sol";
abstract contract BaseMoneyMarketView is IMoneyMarketView {
using LogExpMath for uint256;
string public override moneyMarketName;
IPPTLooper public immutable PT_LOOPER;
IPLoopPositionBoxFactory public immutable POSITION_BOX_FACTORY;
uint256 private constant DAYS_PER_YEAR_SCALED = 365e18;
constructor(string memory _moneyMarketName, address _ptLooper) {
moneyMarketName = _moneyMarketName;
PT_LOOPER = IPPTLooper(_ptLooper);
POSITION_BOX_FACTORY = PT_LOOPER.POSITION_BOX_FACTORY();
}
function moneyMarketBalances(IPLoopPositionBox box)
public
override
returns (uint256 mmPtBalance, uint256 mmDebtBalance)
{
return _moneyMarketBalances(box, _boxData(box));
}
function thresholds(IPLoopPositionBox box)
public
view
override
returns (uint256 ltv, uint256 liquidationThreshold)
{
return _thresholds(box, _boxData(box));
}
function liquidity(IPLoopPositionBox box) public view override returns (uint256 borrowing, uint256 lending) {
return _liquidity(box, _boxData(box));
}
function rewards(IPLoopPositionBox box)
public
override
returns (Reward[] memory borrowing, Reward[] memory lending)
{
return _rewards(box, _boxData(box));
}
function limits(IPLoopPositionBox box) public view override returns (Limits memory limits_) {
return _limits(box, _boxData(box));
}
function rates(IPLoopPositionBox box) public view override returns (uint256 borrowing, uint256 lending) {
return _rates(box, _boxData(box));
}
function ptDebtRate(IPLoopPositionBox box) public view override returns (uint256) {
return _ptDebtRate(box, _boxData(box));
}
function _moneyMarketBalances(IPLoopPositionBox box, BoxData memory bd)
internal
virtual
returns (uint256 mmPtBalance, uint256 mmDebtBalance)
{
IMoneyMarket spokeMM = IMoneyMarket(box.SPOKE_MONEY_MARKET());
MarketCtx memory ctx = createMarketCtx(box, bd);
mmPtBalance = spokeMM.collateralBalance(ctx);
mmDebtBalance = spokeMM.debtBalance(ctx);
}
function _ptDebtRate(IPLoopPositionBox box, BoxData memory bd) internal view virtual returns (uint256) {
return IMoneyMarket(box.SPOKE_MONEY_MARKET()).oraclePtDebtRate(createMarketCtx(box, bd));
}
function _thresholds(IPLoopPositionBox box, BoxData memory bd)
internal
view
virtual
returns (uint256 ltv, uint256 liquidationThreshold);
function _liquidity(IPLoopPositionBox box, BoxData memory bd)
internal
view
virtual
returns (uint256 borrowing, uint256 lending);
function _rates(IPLoopPositionBox box, BoxData memory bd)
internal
view
virtual
returns (uint256 borrowing, uint256 lending);
function _rewards(IPLoopPositionBox box, BoxData memory bd)
internal
virtual
returns (Reward[] memory borrowing, Reward[] memory lending)
{}
function _boxData(IPLoopPositionBox box) internal view virtual returns (BoxData memory) {
return POSITION_BOX_FACTORY.boxData(box.BOX_ID());
}
/// @dev `rate`: WAD interest rate per `perSeconds` seconds (Aave: 365 days; Morpho, Euler: 1).
/// Returns the APY in WAD, compounded daily.
function _apy(uint256 rate, uint256 perSeconds) internal pure returns (uint256) {
uint256 dailyRate = rate * 1 days / perSeconds;
return (dailyRate + PMath.ONE).pow(DAYS_PER_YEAR_SCALED) - PMath.ONE;
}
function _limits(IPLoopPositionBox, BoxData memory) internal view virtual returns (Limits memory limits_) {
limits_.minBorrowing = limits_.minLending = limits_.minBorrowingForRewards = limits_.minLendingForRewards = 0;
limits_.maxBorrowing = limits_.maxLending = type(uint256).max;
}
}
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/AaveV4MMPayloadLib.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {ISpoke} from "./dependencies/ISpoke.sol";
/// @dev Payload, from the high bits: the Spoke address (160), the collateral reserve id (48), the debt reserve
/// id (48).
library AaveV4MMPayloadLib {
function unwrap(bytes32 payload)
internal
pure
returns (ISpoke spoke, uint48 collateralReserveId, uint48 debtReserveId)
{
spoke = ISpoke(address(uint160(uint256(payload) >> (48 + 48))));
collateralReserveId = uint48(uint256(payload) >> 48);
debtReserveId = uint48(uint256(payload));
}
}
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/dependencies/IHubBase.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
/// https://github.com/aave/aave-v4/blob/main/src/hub/interfaces/IHub.sol
/// (and IHubBase.sol, which IHub extends)
/// Modifications:
/// - Trimmed to the read-only surface needed for rate/liquidity display and share<->asset
/// conversion. No mutating Hub functions (add/remove/draw/restore/sweep/reclaim/etc) are called
/// directly by this money market -- all fund movement goes through ISpoke.
interface IHubBase {
struct SpokeData {
uint120 drawnShares;
uint120 premiumShares;
int200 premiumOffsetRay;
uint120 addedShares;
uint40 addCap;
uint40 drawCap;
uint24 riskPremiumThreshold;
bool active;
bool halted;
uint200 deficitRay;
}
struct Asset {
uint120 liquidity;
uint120 realizedFees;
uint8 decimals;
uint120 addedShares;
uint120 swept;
int200 premiumOffsetRay;
uint120 drawnShares;
uint120 premiumShares;
uint16 liquidityFee;
uint120 drawnIndex;
uint96 drawnRate;
uint40 lastUpdateTimestamp;
address underlying;
address irStrategy;
address reinvestmentController;
address feeReceiver;
uint200 deficitRay;
}
/// @notice Current annualized borrow rate for `assetId`, RAY-scaled (1e27) -- same convention
/// as Aave V3's `currentVariableBorrowRate`. There is no supply-rate equivalent; V4 exposes
/// only this one rate primitive.
function getAssetDrawnRate(uint256 assetId) external view returns (uint256);
function getAsset(uint256 assetId) external view returns (Asset memory);
/// @notice Per-(asset, spoke) caps and current usage. `addCap`/`drawCap` are expressed in
/// whole assets (not scaled by decimals); `type(uint40).max` means uncapped.
function getSpoke(uint256 assetId, address spoke) external view returns (SpokeData memory);
function previewRemoveByShares(uint256 assetId, uint256 shares) external view returns (uint256);
function previewRestoreByShares(uint256 assetId, uint256 shares) external view returns (uint256);
/// @notice The asset-level total value backing all `addedShares` (liquidity + swept + owed -
/// fees), already aggregated Hub-side.
/// https://github.com/aave/aave-v4/blob/2524fe4018a42750300e114f2a8c4355df62a878/src/hub/Hub.sol#L513-L515
/// https://github.com/aave/aave-v4/blob/2524fe4018a42750300e114f2a8c4355df62a878/src/hub/libraries/AssetLogic.sol#L79-L96
function getAddedAssets(uint256 assetId) external view returns (uint256);
/// @notice Total amount of `assetId` owed to the Hub by `spoke` (drawn + premium debt,
/// computed internally -- handles the signed premium-offset subtraction itself, so callers
/// never need to touch `SpokeData.premiumOffsetRay`'s sign).
function getSpokeTotalOwed(uint256 assetId, address spoke) external view returns (uint256);
/// @notice Total amount of `assetId` owed to the Hub across all spokes (drawn + premium debt,
/// Hub-wide) -- the asset-level equivalent of `getSpokeTotalOwed`.
function getAssetTotalOwed(uint256 assetId) external view returns (uint256);
}
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/aave-v4/dependencies/ISpoke.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {IHubBase} from "./IHubBase.sol";
/// https://github.com/aave/aave-v4/blob/main/src/spoke/interfaces/ISpoke.sol
/// Modifications:
/// - Trimmed to the structs and functions actually used by EulerMoneyMarket/View's Aave V4
/// equivalent (initialize/lend/borrow/repay/withdraw/collateralBalance/debtBalance/oracle rate,
/// plus thresholds/liquidity view queries). Governance, liquidation, and position-manager
/// surfaces are intentionally omitted -- not called by this money market.
interface ISpoke {
struct Reserve {
address underlying;
IHubBase hub;
uint16 assetId;
uint8 decimals;
uint24 collateralRisk;
uint8 flags;
uint32 dynamicConfigKey;
}
struct DynamicReserveConfig {
uint16 collateralFactor;
uint32 maxLiquidationBonus;
uint16 liquidationFee;
}
struct UserPosition {
uint120 drawnShares;
uint120 premiumShares;
int200 premiumOffsetRay;
uint120 suppliedShares;
uint32 dynamicConfigKey;
}
/// @notice Address of this Spoke's oracle. Public immutable on the real contract (auto-getter).
function ORACLE() external view returns (address);
/// @notice Supplies `amount` of the reserve's underlying, crediting `onBehalfOf`.
/// @dev Caller must be `onBehalfOf` or an approved position manager for it -- `msg.sender ==
/// onBehalfOf` always satisfies this with zero registration, which is the only case we use.
/// @return shares, assets (assets is `amount` echoed back, not a rounded conversion).
function supply(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @return shares, assets actually withdrawn.
function withdraw(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @return shares, assets actually borrowed (echoed back, not rounded).
function borrow(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @return shares, total debt value restored. This is always exactly `min(amount, totalDebt)`:
/// `UserPositionUtils.calculateRestoreAmount` splits `amount` into drawn and premium components
/// whose sum reconstitutes `amount` exactly (or the full debt, when `amount` covers it), and
/// `Spoke.repay` pulls precisely that sum from `msg.sender`.
function repay(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @notice Enables/disables `reserveId` as collateral for `onBehalfOf`.
function setUsingAsCollateral(uint256 reserveId, bool usingAsCollateral, address onBehalfOf) external;
/// @notice Reverts if the reserve associated with `reserveId` is not listed.
function getReserve(uint256 reserveId) external view returns (Reserve memory);
/// @notice Reverts if `reserveId` is not listed; does not revert if `dynamicConfigKey` is unset.
function getDynamicReserveConfig(uint256 reserveId, uint32 dynamicConfigKey)
external
view
returns (DynamicReserveConfig memory);
/// @notice Assets supplied by `user` for `reserveId`, already resolved from shares to assets.
function getUserSuppliedAssets(uint256 reserveId, address user) external view returns (uint256);
/// @notice Total debt (drawn + risk-premium components already summed) owed by `user` for `reserveId`.
function getUserTotalDebt(uint256 reserveId, address user) external view returns (uint256);
/// @notice Per-user, per-reserve position data. `dynamicConfigKey` here is the config version
/// actually pinned to this position -- it can lag `Reserve.dynamicConfigKey` (the reserve's
/// current version) until the position's next `borrow`/`withdraw`/`setUsingAsCollateral(true)`
/// refreshes it. Use this, not `getReserve(...).dynamicConfigKey`, to read the config that's
/// actually enforced for a given position (verified against `Spoke._processUserAccountData`).
function getUserPosition(uint256 reserveId, address user) external view returns (UserPosition memory);
/// @notice The risk premium from `user`'s last position update, in BPS -- a per-position
/// surcharge on top of the reserve's base drawn rate, based on the quality of the collateral
/// backing their debt. Not reflected in `getAssetDrawnRate`, which is Hub-wide/market-level.
function getUserLastRiskPremium(address user) external view returns (uint256);
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@pendle/core-v2/=lib/pendle-core-v2/",
"@pendle/sy/=lib/pendle-sy/",
"forge-std/=lib/forge-std/",
"vendor/=vendor/",
"vendor-locked/=vendor-locked/",
"node_modules/@chainlink/contracts/:@openzeppelin/contracts/=node_modules/@chainlink/contracts/node_modules/@openzeppelin/contracts/",
"@chainlink/=node_modules/@chainlink/",
"@eth-optimism/=node_modules/@eth-optimism/",
"@layerzerolabs/=node_modules/@layerzerolabs/",
"@openzeppelin/=node_modules/@openzeppelin/",
"@pendle/=node_modules/@pendle/",
"hardhat/=node_modules/hardhat/",
"pendle-core-v2/=lib/pendle-core-v2/",
"pendle-sy/=lib/pendle-sy/contracts/",
"solidity-bytes-utils/=node_modules/solidity-bytes-utils/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.