Skip to content
Verified contractPartialBUSL-1.1

MorphoBlueMoneyMarketView

Address0x5b4f97720354f01cbdacdfd6d4e946e7c430ba52
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,751
Creation transaction
0x47fdfc0c08…fe68fb4d89

lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/MorphoBlueMoneyMarketView.sol

//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import {IMorpho, MorphoMarketId, MarketParams, Market as MorphoMarketState} from "./dependencies/IMorpho.sol";
import {BaseMoneyMarketView} from "../../BaseMoneyMarketView.sol";
import {IPLoopPositionBox, BoxData} from "../../../../interfaces/IPLoopPositionBox.sol";
import {IERC20Metadata as IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

contract MorphoBlueMoneyMarketView is BaseMoneyMarketView {
    IMorpho public immutable MORPHO;

    constructor(string memory _moneyMarketName, address _ptLooper, address _morpho)
        BaseMoneyMarketView(_moneyMarketName, _ptLooper)
    {
        MORPHO = IMorpho(_morpho);
    }

    // ========== IMoneyMarketView ==========

    function _thresholds(IPLoopPositionBox, BoxData memory bd)
        internal
        view
        virtual
        override
        returns (uint256 ltv, uint256 liquidationThreshold)
    {
        // Morpho has one LLTV for both.
        ltv = liquidationThreshold = MORPHO.idToMarketParams(_morphoMarketId(bd)).lltv;
    }

    function _liquidity(IPLoopPositionBox, BoxData memory bd)
        internal
        view
        virtual
        override
        returns (uint256 borrowing, uint256 lending)
    {
        MorphoMarketState memory market = MORPHO.market(_morphoMarketId(bd));
        borrowing = market.totalSupplyAssets - market.totalBorrowAssets;
        lending = IERC20(bd.spokePt).totalSupply();
    }

    function _rates(IPLoopPositionBox, BoxData memory bd)
        internal
        view
        virtual
        override
        returns (uint256 borrowing, uint256 lending)
    {
        MorphoMarketId marketId = _morphoMarketId(bd);
        MarketParams memory params = MORPHO.idToMarketParams(marketId);

        borrowing = _apy({rate: params.irm.borrowRateView(params, MORPHO.market(marketId)), perSeconds: 1});
        lending = 0;
    }

    // ========== Other internal helpers ==========

    function _morphoMarketId(BoxData memory bd) internal pure returns (MorphoMarketId) {
        return MorphoMarketId.wrap(bd.mmPayload);
    }
}

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/morpho/dependencies/IMorpho.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.4;

import {IERC20Metadata as IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import "./IMorphoOracle.sol";

type MorphoMarketId is bytes32;

struct MarketParams {
    IERC20 loanToken;
    IERC20 collateralToken;
    IMorphoOracle oracle;
    IIrm irm;
    uint256 lltv;
}

/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
    uint256 supplyShares;
    uint128 borrowShares;
    uint128 collateral;
}

/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

struct Authorization {
    address authorizer;
    address authorized;
    bool isAuthorized;
    uint256 nonce;
    uint256 deadline;
}

struct Signature {
    uint8 v;
    bytes32 r;
    bytes32 s;
}

/// @title IMorpho
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface of Morpho.
interface IMorpho {
    /// @notice The EIP-712 domain separator.
    /// @dev Warning: In case of a hardfork, every EIP-712 signed message based on this domain separator can be reused
    /// on the forked chain because the domain separator would be the same.
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice The owner of the contract.
    /// @dev It has the power to change the owner.
    /// @dev It has the power to set fees on markets and set the fee recipient.
    /// @dev It has the power to enable but not disable IRMs and LLTVs.
    function owner() external view returns (address);

    /// @notice The fee recipient of all markets.
    /// @dev The recipient receives the fees of a given market through a supply position on that market.
    function feeRecipient() external view returns (address);

    /// @notice The state of the position of `user` on the market corresponding to `id`.
    function position(MorphoMarketId id, address user) external view returns (Position memory);

    /// @notice The state of the market corresponding to `id`.
    function market(MorphoMarketId id) external view returns (Market memory);

    /// @notice Whether the `irm` is enabled.
    function isIrmEnabled(address irm) external view returns (bool);

    /// @notice Whether the `lltv` is enabled.
    function isLltvEnabled(uint256 lltv) external view returns (bool);

    /// @notice Whether `authorized` is authorized to modify `authorizer`'s positions.
    /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
    function isAuthorized(address authorizer, address authorized) external view returns (bool);

    /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
    function nonce(address authorizer) external view returns (uint256);

    /// @notice The market params corresponding to `id`.
    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
    function idToMarketParams(MorphoMarketId id) external view returns (MarketParams memory);

    /// @notice Sets `newOwner` as owner of the contract.
    /// @dev Warning: No two-step transfer ownership.
    /// @dev Warning: The owner can be set to the zero address.
    function setOwner(address newOwner) external;

    /// @notice Enables `irm` as a possible IRM for market creation.
    /// @dev Warning: It is not possible to disable an IRM.
    function enableIrm(address irm) external;

    /// @notice Enables `lltv` as a possible LLTV for market creation.
    /// @dev Warning: It is not possible to disable a LLTV.
    function enableLltv(uint256 lltv) external;

    /// @notice Sets the `newFee` for the given market `marketParams`.
    /// @dev Warning: The recipient can be the zero address.
    function setFee(MarketParams memory marketParams, uint256 newFee) external;

    /// @notice Sets `newFeeRecipient` as recipient of the fee.
    /// @dev Warning: The fee recipient can be set to the zero address.
    /// @dev Warning: The fee to be accrued on each market won't belong to the old fee recipient after calling this
    /// function.
    function setFeeRecipient(address newFeeRecipient) external;

    /// @notice Creates the market `marketParams`.
    /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
    /// Morpho behaves as expected:
    /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
    /// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
    /// burn functions are not supported.
    /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
    /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
    /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
    /// - The IRM should not re-enter Morpho.
    /// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties:
    /// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
    /// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
    /// `toSharesDown` overflow.
    /// - The IRM can revert on `borrowRate`.
    /// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
    /// overflow.
    /// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
    /// `liquidate` from being used under certain market conditions.
    /// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
    /// the computation of `assetsRepaid` in `liquidate` overflow.
    function createMarket(MarketParams memory marketParams) external;

    /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoSupply` function with the given `data`.
    /// @dev Either `assets` or `shares` should be zero. Most usecases should rely on `assets` as an input so the caller
    /// is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific amount
    /// of shares is given for full compatibility and precision.
    /// @dev Supplying a large amount can revert for overflow.
    /// @param marketParams The market to supply assets to.
    /// @param assets The amount of assets to supply.
    /// @param shares The amount of shares to mint.
    /// @param onBehalf The address that will own the increased supply position.
    /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
    /// @return assetsSupplied The amount of assets supplied.
    /// @return sharesSupplied The amount of shares minted.
    function supply(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);

    /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` to `receiver`.
    /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
    /// @param marketParams The market to withdraw assets from.
    /// @param assets The amount of assets to withdraw.
    /// @param shares The amount of shares to burn.
    /// @param onBehalf The address of the owner of the supply position.
    /// @param receiver The address that will receive the withdrawn assets.
    /// @return assetsWithdrawn The amount of assets withdrawn.
    /// @return sharesWithdrawn The amount of shares burned.
    function withdraw(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);

    /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` to `receiver`.
    /// @dev Either `assets` or `shares` should be zero. Most usecases should rely on `assets` as an input so the caller
    /// is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is given for
    /// full compatibility and precision.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Borrowing a large amount can revert for overflow.
    /// @param marketParams The market to borrow assets from.
    /// @param assets The amount of assets to borrow.
    /// @param shares The amount of shares to mint.
    /// @param onBehalf The address that will own the increased borrow position.
    /// @param receiver The address that will receive the borrowed assets.
    /// @return assetsBorrowed The amount of assets borrowed.
    /// @return sharesBorrowed The amount of shares minted.
    function borrow(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);

    /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoReplay` function with the given `data`.
    /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
    /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
    /// @param marketParams The market to repay assets to.
    /// @param assets The amount of assets to repay.
    /// @param shares The amount of shares to burn.
    /// @param onBehalf The address of the owner of the debt position.
    /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
    /// @return assetsRepaid The amount of assets repaid.
    /// @return sharesRepaid The amount of shares burned.
    function repay(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);

    /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoSupplyCollateral` function with the given `data`.
    /// @dev Interest are not accrued since it's not required and it saves gas.
    /// @dev Supplying a large amount can revert for overflow.
    /// @param marketParams The market to supply collateral to.
    /// @param assets The amount of collateral to supply.
    /// @param onBehalf The address that will own the increased collateral position.
    /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
    function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
        external;

    /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` to `receiver`.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
    /// @param marketParams The market to withdraw collateral from.
    /// @param assets The amount of collateral to withdraw.
    /// @param onBehalf The address of the owner of the collateral position.
    /// @param receiver The address that will receive the collateral assets.
    function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
        external;

    /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
    /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
    /// `onMorphoLiquidate` function with the given `data`.
    /// @dev Either `seizedAssets` or `repaidShares` should be zero.
    /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
    /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
    /// @param marketParams The market of the position.
    /// @param borrower The owner of the position.
    /// @param seizedAssets The amount of collateral to seize.
    /// @param repaidShares The amount of shares to repay.
    /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
    /// @return The amount of assets seized.
    /// @return The amount of assets repaid.
    function liquidate(
        MarketParams memory marketParams,
        address borrower,
        uint256 seizedAssets,
        uint256 repaidShares,
        bytes memory data
    ) external returns (uint256, uint256);

    /// @notice Executes a flash loan.
    /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
    /// markets combined, plus donations).
    /// @param token The token to flash loan.
    /// @param assets The amount of assets to flash loan.
    /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
    function flashLoan(address token, uint256 assets, bytes calldata data) external;

    /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
    /// @param authorized The authorized address.
    /// @param newIsAuthorized The new authorization status.
    function setAuthorization(address authorized, bool newIsAuthorized) external;

    /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
    /// @dev Warning: Reverts if the signature has already been submitted.
    /// @dev The signature is malleable, but it has no impact on the security here.
    /// @dev The nonce is passed as argument to be able to revert with a different error message.
    /// @param authorization The `Authorization` struct.
    /// @param signature The signature.
    function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;

    /// @notice Returns the data stored on the different `slots`.
    function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);

    /// @notice Accrues interest for the given market `marketParams`.
    function accrueInterest(MarketParams memory marketParams) external;
}

interface IIrm {
    event BorrowRateUpdate(MorphoMarketId indexed id, uint256 avgBorrowRate, uint256 rateAtTarget);

    function MORPHO() external view returns (address);
    function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);
    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
    function rateAtTarget(MorphoMarketId) external view returns (int256);
}

lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/IMorphoOracle.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.4;

/// @title IMorphoOracle
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that oracles used by Morpho must implement.
interface IMorphoOracle {
    /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
    /// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in
    /// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`
    /// decimals of precision.
    function price() 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.