Verified contractPartialBUSL-1.1
MorphoBlueMoneyMarket
Address0x2e2dfc04dbf23bc074fcffe3a716125d45ff39d5
- 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
- 0xcffc1db7f0…3322fb54a9
19 files
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/MorphoBlueMoneyMarket.solmain4.89 KB
- lib/pendle-core-v2/contracts/core/libraries/TokenHelper.sol3.1 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/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/interfaces/IWETH.sol1.45 KB
- lib/pendle-core-v2/contracts/pt-looping/money-market/BaseMoneyMarket.sol2.7 KB
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/IMorpho.sol16.08 KB
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/IMorphoOracle.sol680 B
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/MathLib.sol1.08 KB
- lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/SharesMathLib.sol2.05 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol2.26 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- node_modules/@openzeppelin/contracts/utils/Address.sol9.36 KB
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/MorphoBlueMoneyMarket.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {PMath} from "../../../../core/libraries/math/PMath.sol";
import {MarketCtx} from "../../../../interfaces/IMoneyMarket.sol";
import {BaseMoneyMarket} from "../../BaseMoneyMarket.sol";
import {
IMorpho,
Market as MorphoMarketState,
MarketParams as MorphoMarketParams,
MorphoMarketId,
Position as MorphoPosition
} from "./dependencies/IMorpho.sol";
import {SharesMathLib} from "./dependencies/SharesMathLib.sol";
contract MorphoBlueMoneyMarket is BaseMoneyMarket {
using SharesMathLib for *;
/// @dev The Morpho oracle price is scaled by 1e36; this converts it to WAD.
uint256 internal constant ORACLE_PRICE_SCALE_TO_WAD_DIVISOR = 1e36 / PMath.ONE;
IMorpho public immutable MORPHO;
constructor(address ptLooper, address _morpho) BaseMoneyMarket(ptLooper) {
MORPHO = IMorpho(_morpho);
}
// ========== IMoneyMarket ==========
function _initialize(MarketCtx memory ctx) internal virtual override {
_safeApproveInf(ctx.collateral, address(MORPHO));
_safeApproveInf(ctx.debtAsset, address(MORPHO));
}
function collateralBalance(MarketCtx memory ctx) public view override returns (uint256 balance) {
balance = _selfPosition(ctx.mmPayload).collateral;
}
/// @dev Not `view`: accrues interest before it reads.
function debtBalance(MarketCtx memory ctx) public override returns (uint256 balance) {
MORPHO.accrueInterest(_marketParams(ctx.mmPayload));
MorphoMarketState memory market = _marketState(ctx.mmPayload);
MorphoPosition memory position = _selfPosition(ctx.mmPayload);
balance = position.borrowShares.toAssetsUp(market.totalBorrowAssets, market.totalBorrowShares);
}
function _lend(MarketCtx memory ctx, uint256 amount) internal virtual override returns (uint256 actualAmount) {
_transferIn(ctx.collateral, address(ctx.box), amount);
MORPHO.supplyCollateral({
marketParams: _marketParams(ctx.mmPayload), assets: amount, onBehalf: address(this), data: ""
});
return amount;
}
function _borrow(MarketCtx memory ctx, uint256 amount) internal virtual override returns (uint256 actualAmount) {
(actualAmount,) = MORPHO.borrow({
marketParams: _marketParams(ctx.mmPayload),
assets: amount,
shares: 0,
onBehalf: address(this),
receiver: address(ctx.box)
});
}
/// @dev Pulls exactly the assets Morpho takes to burn `actualShares`. That is at most `amount`, and no
/// dust stays in this contract.
function _repay(MarketCtx memory ctx, uint256 amount, uint256)
internal
virtual
override
returns (uint256 actualAmount)
{
// `BaseMoneyMarket.repay` called `debtBalance`, which accrued interest.
MorphoMarketParams memory marketParams = _marketParams(ctx.mmPayload);
MorphoMarketState memory market = _marketState(ctx.mmPayload);
uint256 borrowShares = _selfPosition(ctx.mmPayload).borrowShares;
uint256 actualShares =
PMath.min(amount.toSharesDown(market.totalBorrowAssets, market.totalBorrowShares), borrowShares);
if (actualShares > 0) {
uint256 pullAmount = actualShares.toAssetsUp(market.totalBorrowAssets, market.totalBorrowShares);
_transferIn(ctx.debtAsset, address(ctx.box), pullAmount);
(actualAmount,) = MORPHO.repay({
marketParams: marketParams, assets: 0, shares: actualShares, onBehalf: address(this), data: ""
});
}
}
function _withdraw(MarketCtx memory ctx, uint256 amount) internal virtual override returns (uint256 actualAmount) {
MORPHO.withdrawCollateral({
marketParams: _marketParams(ctx.mmPayload),
assets: amount,
onBehalf: address(this),
receiver: address(ctx.box)
});
return amount;
}
/// @dev The oracle is per market (`mmPayload`), so `ctx.collateral` and `ctx.debtAsset` are unused.
function oraclePtDebtRate(MarketCtx memory ctx) public view override returns (uint256) {
return _marketParams(ctx.mmPayload).oracle.price() / ORACLE_PRICE_SCALE_TO_WAD_DIVISOR;
}
// ========== Internal helpers ==========
function _marketState(bytes32 mmPayload) internal view returns (MorphoMarketState memory) {
return MORPHO.market(MorphoMarketId.wrap(mmPayload));
}
function _marketParams(bytes32 mmPayload) internal view returns (MorphoMarketParams memory) {
return MORPHO.idToMarketParams(MorphoMarketId.wrap(mmPayload));
}
function _selfPosition(bytes32 mmPayload) internal view returns (MorphoPosition memory) {
return MORPHO.position(MorphoMarketId.wrap(mmPayload), address(this));
}
}
lib/pendle-core-v2/contracts/core/libraries/TokenHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../interfaces/IWETH.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
abstract contract TokenHelper {
using SafeERC20 for IERC20;
address internal constant NATIVE = address(0);
uint256 internal constant LOWER_BOUND_APPROVAL = type(uint96).max / 2; // some tokens use 96 bits for approval
function _transferIn(address token, address from, uint256 amount) internal {
if (token == NATIVE) require(msg.value == amount, "eth mismatch");
else if (amount != 0) IERC20(token).safeTransferFrom(from, address(this), amount);
}
function _transferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount != 0) token.safeTransferFrom(from, to, amount);
}
function _transferOut(address token, address to, uint256 amount) internal {
if (amount == 0 || to == address(this)) return;
if (token == NATIVE) {
(bool success,) = to.call{value: amount}("");
require(success, "eth send failed");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
function _transferOut(address[] memory tokens, address to, uint256[] memory amounts) internal {
uint256 numTokens = tokens.length;
require(numTokens == amounts.length, "length mismatch");
for (uint256 i = 0; i < numTokens;) {
_transferOut(tokens[i], to, amounts[i]);
unchecked {
i++;
}
}
}
function _balanceOf(address addr, address token) internal view returns (uint256) {
return (token == NATIVE) ? addr.balance : IERC20(token).balanceOf(addr);
}
function _selfBalance(address token) internal view returns (uint256) {
return _balanceOf(address(this), token);
}
function _selfBalance(IERC20 token) internal view returns (uint256) {
return token.balanceOf(address(this));
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev PLS PAY ATTENTION to tokens that requires the approval to be set to 0 before changing it
function _safeApprove(address token, address to, uint256 value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "Safe Approve");
}
function _safeApproveInf(address token, address to) internal {
if (token == NATIVE) return;
if (IERC20(token).allowance(address(this), to) < LOWER_BOUND_APPROVAL) {
_safeApprove(token, to, 0);
_safeApprove(token, to, type(uint256).max);
}
}
function _wrap_unwrap_ETH(address tokenIn, address tokenOut, uint256 netTokenIn) internal {
if (tokenIn == NATIVE) IWETH(tokenOut).deposit{value: netTokenIn}();
else IWETH(tokenIn).withdraw(netTokenIn);
}
}
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/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/interfaces/IWETH.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*
* MIT License
* ===========
*
* 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
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
lib/pendle-core-v2/contracts/pt-looping/money-market/BaseMoneyMarket.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {TokenHelper} from "../../core/libraries/TokenHelper.sol";
import {IMoneyMarket, MarketCtx} from "../../interfaces/IMoneyMarket.sol";
import {IPLoopPositionBoxFactory} from "../../interfaces/IPLoopPositionBoxFactory.sol";
import {IPPTLooper} from "../../interfaces/IPPTLooper.sol";
abstract contract BaseMoneyMarket is IMoneyMarket, TokenHelper {
IPPTLooper public immutable PT_LOOPER;
IPLoopPositionBoxFactory public immutable POSITION_BOX_FACTORY;
constructor(address ptLooper) {
PT_LOOPER = IPPTLooper(ptLooper);
POSITION_BOX_FACTORY = PT_LOOPER.POSITION_BOX_FACTORY();
}
modifier onlyPtLooper() {
require(msg.sender == address(PT_LOOPER), "MoneyMarket: unauthorized");
_;
}
modifier onlyPositionBoxFactory() {
require(msg.sender == address(POSITION_BOX_FACTORY), "MoneyMarket: unauthorized");
_;
}
function initialize(MarketCtx memory ctx) external override onlyPositionBoxFactory {
_initialize(ctx);
}
function lend(MarketCtx memory ctx, uint256 amount) external override onlyPtLooper returns (uint256 lent) {
if (amount == 0) return 0;
return _lend(ctx, amount);
}
function withdraw(MarketCtx memory ctx, uint256 amount) external override onlyPtLooper returns (uint256 withdrawn) {
if (amount == 0) return 0;
return _withdraw(ctx, amount);
}
function borrow(MarketCtx memory ctx, uint256 amount) external override onlyPtLooper returns (uint256 borrowed) {
if (amount == 0) return 0;
return _borrow(ctx, amount);
}
function repay(MarketCtx memory ctx, uint256 amount) external override onlyPtLooper returns (uint256 repaid) {
if (amount == 0) return 0;
uint256 balanceBefore = debtBalance(ctx);
if (balanceBefore == 0) return 0;
return _repay(ctx, amount, balanceBefore);
}
// ========== View functions ==========
function debtBalance(MarketCtx memory ctx) public virtual returns (uint256);
// ========== Internal implementation ==========
function _initialize(MarketCtx memory ctx) internal virtual;
function _lend(MarketCtx memory ctx, uint256 amount) internal virtual returns (uint256 actualAmount);
function _withdraw(MarketCtx memory ctx, uint256 amount) internal virtual returns (uint256 actualAmount);
function _borrow(MarketCtx memory ctx, uint256 amount) internal virtual returns (uint256 actualAmount);
function _repay(MarketCtx memory ctx, uint256 amount, uint256 balanceBefore)
internal
virtual
returns (uint256 actualAmount);
}
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);
}
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/MathLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.4;
uint256 constant WAD = 1e18;
/// @title MathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to manage fixed-point arithmetic.
library MathLib {
/// @dev (x * y) / WAD rounded down.
function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD);
}
/// @dev (x * WAD) / y rounded down.
function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y);
}
/// @dev (x * WAD) / y rounded up.
function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y);
}
/// @dev (x * y) / d rounded down.
function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
return (x * y) / d;
}
/// @dev (x * y) / d rounded up.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
return (x * y + (d - 1)) / d;
}
}
lib/pendle-core-v2/contracts/pt-looping/money-market/implementations/morpho/dependencies/SharesMathLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.4;
import {MathLib} from "./MathLib.sol";
/// @title SharesMathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
using MathLib for uint256;
/// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
/// high precision computations.
uint256 internal constant VIRTUAL_SHARES = 1e6;
/// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
/// empty.
uint256 internal constant VIRTUAL_ASSETS = 1;
/// @dev Calculates the value of `assets` quoted in shares, rounding down.
function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding down.
function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
/// @dev Calculates the value of `assets` quoted in shares, rounding up.
function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding up.
function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
}
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);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
node_modules/@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
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.