Morpho Optimizers V1

Morpho-Compound-Optimizer Morpho-AaveV2-Optimizer


What are Morpho Optimizers?

Morpho Optimizers improve the capital efficiency of positions on existing lending pools by seamlessly matching users peer-to-peer.

  • Morpho's rates stay between the supply rate and the borrow rate of the pool, reducing the interest paid by the borrowers while increasing the interest earned by the suppliers. It means that you are getting boosted peer-to-peer rates or, in the worst-case scenario, the APY of the pool.
  • Morpho also preserves the same experience, the same liquidity, and the same parameters (collateral factors, oracles, …) as the underlying pool.

TL;DR: Instead of borrowing or lending on your favorite pool like Compound or Aave, you would be better off using Morpho Optimizers.


Contracts overview

Morpho Optimizers are designed at their core with a set of contracts delegating calls to implementation contracts (to overcome the contract size limit).

Here is a brief overview of the Morpho Optimizers' contracts interactions:

image

The main user's entry points are exposed in the Morpho contract. It inherits from MorphoGovernance, which contains all the admin functions of the DAO, MorphoUtils, and MorphoStorage, where the protocol's storage is located. This contract delegates call to other contracts that have the same storage layout:

  • PositionsManager: logic of basic supply, borrow, withdraw, repay, and liquidate functions. The Morpho-AaveV2 Optimizer is separated into two contracts, EntryPositionsManager and ExitPositionsManager. These contracts inherit from MatchingEngine, which contains the matching engine's internal functions.
  • InterestRatesManager: logic of indexes computation.

It also interacts with RewardsManager, which manages the underlying pool's rewards, if any.


Documentation


Audits

All audits are stored in the audits' folder.


Bug bounty

A bug bounty is open on Immunefi. The rewards and scope are defined here. You can email security@morpho.org if you find something worrying.


Deployment Addresses

Morpho-Compound Optimizer on Ethereum

Morpho-AaveV2 Optimizer on Ethereum

Common Ethereum


Importing package

Using npm:

npm install @morpho-dao/morpho-v1

Using forge:

forge install @morpho-dao/morpho-v1@v2.0.0

Using git submodules:

git submodule add @morpho-dao/morpho-v1@v2.0.0 lib/morpho-v1

Testing with Foundry 🔨

Tests are run against a fork of real networks, allowing us to interact directly with Compound or Aave liquidity pools. Note that you need an RPC provider with access to Ethereum or Polygon.

For testing, make sure yarn and foundry are installed and install dependencies (node_modules, git submodules) with:

make install

Alternatively, if you only want to set up

Refer to the env.example for the required environment variable.

To run tests on different protocols, navigate a Unix terminal to the root folder of the project and run the command of your choice:

To run every test of a specific protocol (e.g. for the Morpho-Compound Optimizer):

make test PROTOCOL=compound

or to run only a specific set of tests of a specific protocol (e.g. for the Morpho-AaveV2 Optimizer):

make c-TestBorrow PROTOCOL=aave-v2

or to run an individual test of a specific protocol (e.g. for the Morpho-AaveV2 Optimizer):

make test-testBorrow1 PROTOCOL=aave-v2

For the other commands, check the Makefile.

If you want to call a custom forge command and not have to edit the Makefile, you can source the export_env.sh script by calling . ./export_env.sh.

:warning: The export_env.sh script exports environment variables in the current shell, meaning that subsequent calls to make or forge will use those variables. Variables defined in the .env.local file will still override those if you run make later. If you don't want to change variables in the current shell, you can always create a new shell in one of the following ways:

  • use ( . ./export_env.sh && forge test ) if the command you want to run is forge test
  • use bash and then . ./export_env.sh followed by your commands and then exit to return to the parent shell and clear the environment variables.

Testing with Hardhat

Only tests for the RewardsDistributor are run with Hardhat.

Just run:

yarn test

Test coverage

Test coverage is reported using foundry coverage with lcov report formatting (and optionally, genhtml transformer).

To generate the lcov report, run the following:

make coverage

The report is then usable either:

:warning: Test coverage is not available on the Morpho-AaveV2 Optimizer for this reason


Storage seatbelt

2 CI pipelines are currently running on every PR to check that the changes introduced are not modifying the storage layout of proxied smart contracts in an unsafe way:

  • storage-layout.sh checks that the latest foundry storage layout snapshot is identical to the committed storage layout snapshot
  • foundry-storage-check is in test phase and will progressively replace the snapshot check

In the case the storage layout snapshots checked by storage-layout.sh are not identical, the developer must commit the updated storage layout snapshot stored under snapshots/ by running:

  • make storage-layout-generate with the appropriate protocol parameters

Deployment & Upgrades

Network mode (default)

Run the Foundry deployment script with:

make script-Deploy PROTOCOL=compound NETWORK=goerli

Local mode

First start a local EVM:

make anvil NETWORK=goerli

Then run the Foundry deployment script in a separate shell, using SMODE=local:

make script-Deploy PROTOCOL=compound NETWORK=goerli SMODE=local

Questions & Feedback

For any questions or feedback, you can send an email to merlin@morpho.org.


Licensing

The code is under the GNU AFFERO GENERAL PUBLIC LICENSE v3.0, see LICENSE.

Contents

Contents

Contents

IAToken

Git Source

Inherits: IERC20, IScaledBalanceToken

Functions

mint

Mints amount aTokens to user

function mint(address user, uint256 amount, uint256 index) external returns (bool);

Parameters

NameTypeDescription
useraddressThe address receiving the minted tokens
amountuint256The amount of tokens getting minted
indexuint256The new liquidity index of the reserve

Returns

NameTypeDescription
<none>booltrue if the the previous balance of the user was 0

burn

Burns aTokens from user and sends the equivalent amount of underlying to receiverOfUnderlying

function burn(address user, address receiverOfUnderlying, uint256 amount, uint256 index) external;

Parameters

NameTypeDescription
useraddressThe owner of the aTokens, getting them burned
receiverOfUnderlyingaddressThe address that will receive the underlying
amountuint256The amount being burned
indexuint256The new liquidity index of the reserve

mintToTreasury

Mints aTokens to the reserve treasury

function mintToTreasury(uint256 amount, uint256 index) external;

Parameters

NameTypeDescription
amountuint256The amount of tokens getting minted
indexuint256The new liquidity index of the reserve

transferOnLiquidation

Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken

function transferOnLiquidation(address from, address to, uint256 value) external;

Parameters

NameTypeDescription
fromaddressThe address getting liquidated, current owner of the aTokens
toaddressThe recipient
valueuint256The amount of tokens getting transferred

transferUnderlyingTo

Transfers the underlying asset to target. Used by the LendingPool to transfer assets in borrow(), withdraw() and flashLoan()

function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);

Parameters

NameTypeDescription
useraddressThe recipient of the aTokens
amountuint256The amount getting transferred

Returns

NameTypeDescription
<none>uint256The amount transferred

UNDERLYING_ASSET_ADDRESS

function UNDERLYING_ASSET_ADDRESS() external view returns (address);

Events

Mint

Emitted after the mint action

event Mint(address indexed from, uint256 value, uint256 index);

Burn

Emitted after aTokens are burned

event Burn(address indexed from, address indexed target, uint256 value, uint256 index);

BalanceTransfer

Emitted during the transfer action

event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);

IERC20

Git Source

Interface of the ERC20 standard as defined in the EIP.

Functions

totalSupply

Returns the amount of tokens in existence.

function totalSupply() external view returns (uint256);

balanceOf

Returns the amount of tokens owned by account.

function balanceOf(address account) external view returns (uint256);

transfer

Moves amount tokens from the caller's account to recipient. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event.

function transfer(address recipient, uint256 amount) external returns (bool);

allowance

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);

approve

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);

transferFrom

Moves amount tokens from sender to recipient 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 sender, address recipient, uint256 amount) external returns (bool);

Events

Transfer

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);

Approval

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);

ILendingPool

Git Source

Functions

deposit

*Deposits an amount of underlying asset into the reserve, receiving in return overlying aTokens.

  • E.g. User deposits 100 USDC and gets in return 100 aUSDC*
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset to deposit
amountuint256The amount to be deposited
onBehalfOfaddressThe address that will receive the aTokens, same as msg.sender if the user wants to receive them on his own wallet, or a different address if the beneficiary of aTokens is a different wallet
referralCodeuint16Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man

withdraw

Withdraws an amount of underlying asset from the reserve, burning the equivalent aTokens owned E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC

function withdraw(address asset, uint256 amount, address to) external returns (uint256);

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset to withdraw
amountuint256The underlying amount to be withdrawn - Send the value type(uint256).max in order to withdraw the whole aToken balance
toaddressAddress that will receive the underlying, same as msg.sender if the user wants to receive it on his own wallet, or a different address if the beneficiary is a different wallet

Returns

NameTypeDescription
<none>uint256The final amount withdrawn

borrow

*Allows users to borrow a specific amount of the reserve underlying asset, provided that the borrower already deposited enough collateral, or he was given enough allowance by a credit delegator on the corresponding debt token (StableDebtToken or VariableDebtToken)

  • E.g. User borrows 100 USDC passing as onBehalfOf his own address, receiving the 100 USDC in his wallet and 100 stable/variable debt tokens, depending on the interestRateMode*
function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf)
    external;

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset to borrow
amountuint256The amount to be borrowed
interestRateModeuint256The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
referralCodeuint16Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man
onBehalfOfaddressAddress of the user who will receive the debt. Should be the address of the borrower itself calling the function if he wants to borrow against his own collateral, or the address of the credit delegator if he has been given credit delegation allowance

repay

Repays a borrowed amount on a specific reserve, burning the equivalent debt tokens owned

  • E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the onBehalfOf address
function repay(address asset, uint256 amount, uint256 rateMode, address onBehalfOf) external returns (uint256);

Parameters

NameTypeDescription
assetaddressThe address of the borrowed underlying asset previously borrowed
amountuint256The amount to repay - Send the value type(uint256).max in order to repay the whole debt for asset on the specific debtMode
rateModeuint256The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
onBehalfOfaddressAddress of the user who will get his debt reduced/removed. Should be the address of the user calling the function if he wants to reduce/remove his own debt, or the address of any other other borrower whose debt should be removed

Returns

NameTypeDescription
<none>uint256The final amount repaid

swapBorrowRateMode

Allows a borrower to swap his debt between stable and variable mode, or viceversa

function swapBorrowRateMode(address asset, uint256 rateMode) external;

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset borrowed
rateModeuint256The rate mode that the user wants to swap to

rebalanceStableBorrowRate

*Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.

  • Users can be rebalanced if the following conditions are satisfied:
  1. Usage ratio is above 95%
  2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been borrowed at a stable rate and depositors are not earning enough*
function rebalanceStableBorrowRate(address asset, address user) external;

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset borrowed
useraddressThe address of the user to be rebalanced

setUserUseReserveAsCollateral

Allows depositors to enable/disable a specific deposited asset as collateral

function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset deposited
useAsCollateralbooltrue if the user wants to use the deposit as collateral, false otherwise

liquidationCall

*Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1

  • The caller (liquidator) covers debtToCover amount of debt of the user getting liquidated, and receives a proportionally amount of the collateralAsset plus a bonus to cover market risk*
function liquidationCall(
    address collateralAsset,
    address debtAsset,
    address user,
    uint256 debtToCover,
    bool receiveAToken
) external;

Parameters

NameTypeDescription
collateralAssetaddressThe address of the underlying asset used as collateral, to receive as result of the liquidation
debtAssetaddressThe address of the underlying borrowed asset to be repaid with the liquidation
useraddressThe address of the borrower getting liquidated
debtToCoveruint256The debt amount of borrowed asset the liquidator wants to cover
receiveATokenbooltrue if the liquidators wants to receive the collateral aTokens, false if he wants to receive the underlying collateral asset directly

flashLoan

Allows smartcontracts to access the liquidity of the pool within one transaction, as long as the amount taken plus a fee is returned. IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. For further details please visit https://developers.aave.com

function flashLoan(
    address receiverAddress,
    address[] calldata assets,
    uint256[] calldata amounts,
    uint256[] calldata modes,
    address onBehalfOf,
    bytes calldata params,
    uint16 referralCode
) external;

Parameters

NameTypeDescription
receiverAddressaddressThe address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
assetsaddress[]The addresses of the assets being flash-borrowed
amountsuint256[]The amounts amounts being flash-borrowed
modesuint256[]Types of the debt to open if the flash loan is not returned: 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the onBehalfOf address 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the onBehalfOf address
onBehalfOfaddressThe address that will receive the debt in the case of using on modes 1 or 2
paramsbytesVariadic packed params to pass to the receiver as extra information
referralCodeuint16Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man

getUserAccountData

Returns the user account data across all the reserves

function getUserAccountData(address user)
    external
    view
    returns (
        uint256 totalCollateralETH,
        uint256 totalDebtETH,
        uint256 availableBorrowsETH,
        uint256 currentLiquidationThreshold,
        uint256 ltv,
        uint256 healthFactor
    );

Parameters

NameTypeDescription
useraddressThe address of the user

Returns

NameTypeDescription
totalCollateralETHuint256the total collateral in ETH of the user
totalDebtETHuint256the total debt in ETH of the user
availableBorrowsETHuint256the borrowing power left of the user
currentLiquidationThresholduint256the liquidation threshold of the user
ltvuint256the loan to value of the user
healthFactoruint256the current health factor of the user

initReserve

function initReserve(
    address reserve,
    address aTokenAddress,
    address stableDebtAddress,
    address variableDebtAddress,
    address interestRateStrategyAddress
) external;

setReserveInterestRateStrategyAddress

function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external;

setConfiguration

function setConfiguration(address reserve, uint256 configuration) external;

getConfiguration

Returns the configuration of the reserve

function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset of the reserve

Returns

NameTypeDescription
<none>DataTypes.ReserveConfigurationMapThe configuration of the reserve

getUserConfiguration

Returns the configuration of the user across all the reserves

function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);

Parameters

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
<none>DataTypes.UserConfigurationMapThe configuration of the user

getReserveNormalizedIncome

Returns the normalized income normalized income of the reserve

function getReserveNormalizedIncome(address asset) external view returns (uint256);

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset of the reserve

Returns

NameTypeDescription
<none>uint256The reserve's normalized income

getReserveNormalizedVariableDebt

Returns the normalized variable debt per unit of asset

function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset of the reserve

Returns

NameTypeDescription
<none>uint256The reserve normalized variable debt

getReserveData

Returns the state and configuration of the reserve

function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);

Parameters

NameTypeDescription
assetaddressThe address of the underlying asset of the reserve

Returns

NameTypeDescription
<none>DataTypes.ReserveDataThe state of the reserve

finalizeTransfer

function finalizeTransfer(
    address asset,
    address from,
    address to,
    uint256 amount,
    uint256 balanceFromAfter,
    uint256 balanceToBefore
) external;

getReservesList

function getReservesList() external view returns (address[] memory);

getAddressesProvider

function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);

setPause

function setPause(bool val) external;

paused

function paused() external view returns (bool);

FLASHLOAN_PREMIUM_TOTAL

function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint256);

Events

Deposit

Emitted on deposit()

event Deposit(
    address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral
);

Withdraw

Emitted on withdraw()

event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);

Borrow

Emitted on borrow() and flashLoan() when debt needs to be opened

event Borrow(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    uint256 borrowRateMode,
    uint256 borrowRate,
    uint16 indexed referral
);

Repay

Emitted on repay()

event Repay(address indexed reserve, address indexed user, address indexed repayer, uint256 amount);

Swap

Emitted on swapBorrowRateMode()

event Swap(address indexed reserve, address indexed user, uint256 rateMode);

ReserveUsedAsCollateralEnabled

Emitted on setUserUseReserveAsCollateral()

event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);

ReserveUsedAsCollateralDisabled

Emitted on setUserUseReserveAsCollateral()

event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);

RebalanceStableBorrowRate

Emitted on rebalanceStableBorrowRate()

event RebalanceStableBorrowRate(address indexed reserve, address indexed user);

FlashLoan

Emitted on flashLoan()

event FlashLoan(
    address indexed target,
    address indexed initiator,
    address indexed asset,
    uint256 amount,
    uint256 premium,
    uint16 referralCode
);

Paused

Emitted when the pause is triggered.

event Paused();

Unpaused

Emitted when the pause is lifted.

event Unpaused();

LiquidationCall

Emitted when a borrower is liquidated. This event is emitted by the LendingPool via LendingPoolCollateral manager using a DELEGATECALL This allows to have the events in the generated ABI for LendingPool.

event LiquidationCall(
    address indexed collateralAsset,
    address indexed debtAsset,
    address indexed user,
    uint256 debtToCover,
    uint256 liquidatedCollateralAmount,
    address liquidator,
    bool receiveAToken
);

ReserveDataUpdated

Emitted when the state of a reserve is updated. NOTE: This event is actually declared in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it gets added to the LendingPool ABI

event ReserveDataUpdated(
    address indexed reserve,
    uint256 liquidityRate,
    uint256 stableBorrowRate,
    uint256 variableBorrowRate,
    uint256 liquidityIndex,
    uint256 variableBorrowIndex
);

ILendingPoolAddressesProvider

Git Source

Author: Aave

*Main registry of addresses part of or connected to the protocol, including permissioned roles

  • Acting also as factory of proxies and admin of those, so with right to change its implementations
  • Owned by the Aave Governance*

Functions

getMarketId

function getMarketId() external view returns (string memory);

setMarketId

function setMarketId(string calldata marketId) external;

setAddress

function setAddress(bytes32 id, address newAddress) external;

setAddressAsProxy

function setAddressAsProxy(bytes32 id, address impl) external;

getAddress

function getAddress(bytes32 id) external view returns (address);

getLendingPool

function getLendingPool() external view returns (address);

setLendingPoolImpl

function setLendingPoolImpl(address pool) external;

getLendingPoolConfigurator

function getLendingPoolConfigurator() external view returns (address);

setLendingPoolConfiguratorImpl

function setLendingPoolConfiguratorImpl(address configurator) external;

getLendingPoolCollateralManager

function getLendingPoolCollateralManager() external view returns (address);

setLendingPoolCollateralManager

function setLendingPoolCollateralManager(address manager) external;

getPoolAdmin

function getPoolAdmin() external view returns (address);

setPoolAdmin

function setPoolAdmin(address admin) external;

getEmergencyAdmin

function getEmergencyAdmin() external view returns (address);

setEmergencyAdmin

function setEmergencyAdmin(address admin) external;

getPriceOracle

function getPriceOracle() external view returns (address);

setPriceOracle

function setPriceOracle(address priceOracle) external;

getLendingRateOracle

function getLendingRateOracle() external view returns (address);

setLendingRateOracle

function setLendingRateOracle(address lendingRateOracle) external;

Events

MarketIdSet

event MarketIdSet(string newMarketId);

LendingPoolUpdated

event LendingPoolUpdated(address indexed newAddress);

ConfigurationAdminUpdated

event ConfigurationAdminUpdated(address indexed newAddress);

EmergencyAdminUpdated

event EmergencyAdminUpdated(address indexed newAddress);

LendingPoolConfiguratorUpdated

event LendingPoolConfiguratorUpdated(address indexed newAddress);

LendingPoolCollateralManagerUpdated

event LendingPoolCollateralManagerUpdated(address indexed newAddress);

PriceOracleUpdated

event PriceOracleUpdated(address indexed newAddress);

LendingRateOracleUpdated

event LendingRateOracleUpdated(address indexed newAddress);

ProxyCreated

event ProxyCreated(bytes32 id, address indexed newAddress);

AddressSet

event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);

IPriceOracleGetter

Git Source

Interface for the Aave price oracle.

Functions

getAssetPrice

returns the asset price in ETH

function getAssetPrice(address _asset) external view returns (uint256);

IReserveInterestRateStrategy

Git Source

Functions

baseVariableBorrowRate

function baseVariableBorrowRate() external view returns (uint256);

getMaxVariableBorrowRate

function getMaxVariableBorrowRate() external view returns (uint256);

calculateInterestRates

function calculateInterestRates(
    address reserve,
    uint256 utilizationRate,
    uint256 totalStableDebt,
    uint256 totalVariableDebt,
    uint256 averageStableBorrowRate,
    uint256 reserveFactor
) external view returns (uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate);

IScaledBalanceToken

Git Source

Functions

scaledBalanceOf

Returns the scaled balance of the user. The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index at the moment of the update

function scaledBalanceOf(address user) external view returns (uint256);

Parameters

NameTypeDescription
useraddressThe user whose balance is calculated

Returns

NameTypeDescription
<none>uint256The scaled balance of the user

getScaledUserBalanceAndSupply

Returns the scaled balance of the user and the scaled total supply.

function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);

Parameters

NameTypeDescription
useraddressThe address of the user

Returns

NameTypeDescription
<none>uint256The scaled balance of the user
<none>uint256The scaled balance and the scaled total supply

scaledTotalSupply

Returns the scaled total supply of the variable debt token. Represents sum(debt/index)

function scaledTotalSupply() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The scaled total supply

IStableDebtToken

Git Source

Author: Aave

Defines the interface for the stable debt token

Functions

mint

Mints debt token to the onBehalfOf address.

The resulting rate is the weighted average between the rate of the new debt and the rate of the previous debt

function mint(address user, address onBehalfOf, uint256 amount, uint256 rate)
    external
    returns (bool, uint256, uint256);

Parameters

NameTypeDescription
useraddressThe address receiving the borrowed underlying, being the delegatee in case of credit delegate, or same as onBehalfOf otherwise
onBehalfOfaddressThe address receiving the debt tokens
amountuint256The amount of debt tokens to mint
rateuint256The rate of the debt being minted

Returns

NameTypeDescription
<none>boolTrue if it is the first borrow, false otherwise
<none>uint256The total stable debt
<none>uint256The average stable borrow rate

burn

Burns debt of user

The resulting rate is the weighted average between the rate of the new debt and the rate of the previous debt

In some instances, a burn transaction will emit a mint event if the amount to burn is less than the interest the user earned

function burn(address from, uint256 amount) external returns (uint256, uint256);

Parameters

NameTypeDescription
fromaddressThe address from which the debt will be burned
amountuint256The amount of debt tokens getting burned

Returns

NameTypeDescription
<none>uint256The total stable debt
<none>uint256The average stable borrow rate

getAverageStableRate

Returns the average rate of all the stable rate loans.

function getAverageStableRate() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The average stable rate

getUserStableRate

Returns the stable rate of the user debt

function getUserStableRate(address user) external view returns (uint256);

Parameters

NameTypeDescription
useraddressThe address of the user

Returns

NameTypeDescription
<none>uint256The stable rate of the user

getUserLastUpdated

Returns the timestamp of the last update of the user

function getUserLastUpdated(address user) external view returns (uint40);

Parameters

NameTypeDescription
useraddressThe address of the user

Returns

NameTypeDescription
<none>uint40The timestamp

getSupplyData

Returns the principal, the total supply, the average stable rate and the timestamp for the last update

function getSupplyData() external view returns (uint256, uint256, uint256, uint40);

Returns

NameTypeDescription
<none>uint256The principal
<none>uint256The total supply
<none>uint256The average stable rate
<none>uint40The timestamp of the last update

getTotalSupplyLastUpdated

Returns the timestamp of the last update of the total supply

function getTotalSupplyLastUpdated() external view returns (uint40);

Returns

NameTypeDescription
<none>uint40The timestamp

getTotalSupplyAndAvgRate

Returns the total supply and the average stable rate

function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);

Returns

NameTypeDescription
<none>uint256The total supply
<none>uint256The average rate

principalBalanceOf

Returns the principal debt balance of the user

function principalBalanceOf(address user) external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The debt balance of the user since the last burn/mint action

UNDERLYING_ASSET_ADDRESS

Returns the address of the underlying asset of this stableDebtToken (E.g. WETH for stableDebtWETH)

function UNDERLYING_ASSET_ADDRESS() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the underlying asset

Events

Mint

Emitted when new stable debt is minted

event Mint(
    address indexed user,
    address indexed onBehalfOf,
    uint256 amount,
    uint256 currentBalance,
    uint256 balanceIncrease,
    uint256 newRate,
    uint256 avgStableRate,
    uint256 newTotalSupply
);

Burn

Emitted when new stable debt is burned

event Burn(
    address indexed from,
    uint256 amount,
    uint256 currentBalance,
    uint256 balanceIncrease,
    uint256 avgStableRate,
    uint256 newTotalSupply
);

IVariableDebtToken

Git Source

Inherits: IScaledBalanceToken

Author: Aave

Defines the basic interface for a variable debt token.

Functions

approveDelegation

delegates borrowing power to a user on the specific debt token

function approveDelegation(address delegatee, uint256 amount) external;

Parameters

NameTypeDescription
delegateeaddressthe address receiving the delegated borrowing power
amountuint256the maximum amount being delegated. Delegation will still respect the liquidation constraints (even if delegated, a delegatee cannot force a delegator HF to go below 1)

borrowAllowance

returns the borrow allowance of the user

function borrowAllowance(address fromUser, address toUser) external view returns (uint256);

Parameters

NameTypeDescription
fromUseraddressThe user to giving allowance
toUseraddressThe user to give allowance to

Returns

NameTypeDescription
<none>uint256the current allowance of toUser

mint

Mints debt token to the onBehalfOf address

function mint(address user, address onBehalfOf, uint256 amount, uint256 index) external returns (bool);

Parameters

NameTypeDescription
useraddressThe address receiving the borrowed underlying, being the delegatee in case of credit delegate, or same as onBehalfOf otherwise
onBehalfOfaddressThe address receiving the debt tokens
amountuint256The amount of debt being minted
indexuint256The variable debt index of the reserve

Returns

NameTypeDescription
<none>booltrue if the the previous balance of the user is 0

burn

Burns user variable debt

function burn(address user, uint256 amount, uint256 index) external;

Parameters

NameTypeDescription
useraddressThe user which debt is burnt
amountuint256
indexuint256The variable debt index of the reserve

balanceOf

Returns the debt balance of the user

function balanceOf(address user) external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The debt balance of the user.

Events

Mint

Emitted after the mint action

event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);

Burn

Emitted when variable debt is burnt

event Burn(address indexed user, uint256 amount, uint256 index);

Contents

ILido

Git Source

Functions

getPooledEthByShares

function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256);

submit

function submit(address _referral) external payable returns (uint256);

IEntryPositionsManager

Git Source

Functions

supplyLogic

function supplyLogic(
    address _poolToken,
    address _supplier,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) external;

borrowLogic

function borrowLogic(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;

IExitPositionsManager

Git Source

Functions

withdrawLogic

function withdrawLogic(
    address _poolToken,
    uint256 _amount,
    address _supplier,
    address _receiver,
    uint256 _maxGasForMatching
) external;

repayLogic

function repayLogic(
    address _poolToken,
    address _repayer,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) external;

liquidateLogic

function liquidateLogic(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external;

increaseP2PDeltasLogic

function increaseP2PDeltasLogic(address _poolToken, uint256 _amount) external;

IGetterUnderlyingAsset

Git Source

Functions

UNDERLYING_ASSET_ADDRESS

function UNDERLYING_ASSET_ADDRESS() external view returns (address);

IInterestRatesManager

Git Source

Functions

updateIndexes

function updateIndexes(address _marketAddress) external;

IMorpho

Git Source

Functions

NO_REFERRAL_CODE

STORAGE ///

function NO_REFERRAL_CODE() external view returns (uint8);

VARIABLE_INTEREST_MODE

function VARIABLE_INTEREST_MODE() external view returns (uint8);

MAX_BASIS_POINTS

function MAX_BASIS_POINTS() external view returns (uint16);

DEFAULT_LIQUIDATION_CLOSE_FACTOR

function DEFAULT_LIQUIDATION_CLOSE_FACTOR() external view returns (uint256);

HEALTH_FACTOR_LIQUIDATION_THRESHOLD

function HEALTH_FACTOR_LIQUIDATION_THRESHOLD() external view returns (uint256);

MAX_NB_OF_MARKETS

function MAX_NB_OF_MARKETS() external view returns (uint256);

BORROWING_MASK

function BORROWING_MASK() external view returns (bytes32);

ONE

function ONE() external view returns (bytes32);

ST_ETH

function ST_ETH() external view returns (address);

ST_ETH_BASE_REBASE_INDEX

function ST_ETH_BASE_REBASE_INDEX() external view returns (uint256);

isClaimRewardsPaused

function isClaimRewardsPaused() external view returns (bool);

defaultMaxGasForMatching

function defaultMaxGasForMatching() external view returns (Types.MaxGasForMatching memory);

maxSortedUsers

function maxSortedUsers() external view returns (uint256);

supplyBalanceInOf

function supplyBalanceInOf(address, address) external view returns (Types.SupplyBalance memory);

borrowBalanceInOf

function borrowBalanceInOf(address, address) external view returns (Types.BorrowBalance memory);

deltas

function deltas(address) external view returns (Types.Delta memory);

market

function market(address) external view returns (Types.Market memory);

marketPauseStatus

function marketPauseStatus(address) external view returns (Types.MarketPauseStatus memory);

p2pSupplyIndex

function p2pSupplyIndex(address) external view returns (uint256);

p2pBorrowIndex

function p2pBorrowIndex(address) external view returns (uint256);

poolIndexes

function poolIndexes(address) external view returns (Types.PoolIndexes memory);

interestRatesManager

function interestRatesManager() external view returns (IInterestRatesManager);

entryPositionsManager

function entryPositionsManager() external view returns (IEntryPositionsManager);

exitPositionsManager

function exitPositionsManager() external view returns (IExitPositionsManager);

addressesProvider

function addressesProvider() external view returns (ILendingPoolAddressesProvider);

pool

function pool() external view returns (ILendingPool);

treasuryVault

function treasuryVault() external view returns (address);

borrowMask

function borrowMask(address) external view returns (bytes32);

userMarkets

function userMarkets(address) external view returns (bytes32);

updateIndexes

UTILS ///

function updateIndexes(address _poolToken) external;

getMarketsCreated

GETTERS ///

function getMarketsCreated() external view returns (address[] memory marketsCreated_);

getHead

function getHead(address _poolToken, Types.PositionType _positionType) external view returns (address head);

getNext

function getNext(address _poolToken, Types.PositionType _positionType, address _user)
    external
    view
    returns (address next);

setMaxSortedUsers

GOVERNANCE ///

function setMaxSortedUsers(uint256 _newMaxSortedUsers) external;

setDefaultMaxGasForMatching

function setDefaultMaxGasForMatching(Types.MaxGasForMatching memory _maxGasForMatching) external;

setExitPositionsManager

function setExitPositionsManager(IExitPositionsManager _exitPositionsManager) external;

setEntryPositionsManager

function setEntryPositionsManager(IEntryPositionsManager _entryPositionsManager) external;

setInterestRatesManager

function setInterestRatesManager(IInterestRatesManager _interestRatesManager) external;

setTreasuryVault

function setTreasuryVault(address _newTreasuryVaultAddress) external;

setIsP2PDisabled

function setIsP2PDisabled(address _poolToken, bool _isP2PDisabled) external;

setReserveFactor

function setReserveFactor(address _poolToken, uint256 _newReserveFactor) external;

setP2PIndexCursor

function setP2PIndexCursor(address _poolToken, uint16 _p2pIndexCursor) external;

setIsPausedForAllMarkets

function setIsPausedForAllMarkets(bool _isPaused) external;

setIsSupplyPaused

function setIsSupplyPaused(address _poolToken, bool _isPaused) external;

setIsBorrowPaused

function setIsBorrowPaused(address _poolToken, bool _isPaused) external;

setIsWithdrawPaused

function setIsWithdrawPaused(address _poolToken, bool _isPaused) external;

setIsRepayPaused

function setIsRepayPaused(address _poolToken, bool _isPaused) external;

setIsLiquidateCollateralPaused

function setIsLiquidateCollateralPaused(address _poolToken, bool _isPaused) external;

setIsLiquidateBorrowPaused

function setIsLiquidateBorrowPaused(address _poolToken, bool _isPaused) external;

claimToTreasury

function claimToTreasury(address[] calldata _poolTokens, uint256[] calldata _amounts) external;

createMarket

function createMarket(address _underlyingToken, uint16 _reserveFactor, uint16 _p2pIndexCursor) external;

increaseP2PDeltas

function increaseP2PDeltas(address _poolToken, uint256 _amount) external;

supply

USERS ///

function supply(address _poolToken, uint256 _amount) external;

supply

function supply(address _poolToken, address _onBehalf, uint256 _amount) external;

supply

function supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) external;

borrow

function borrow(address _poolToken, uint256 _amount) external;

borrow

function borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;

withdraw

function withdraw(address _poolToken, uint256 _amount) external;

withdraw

function withdraw(address _poolToken, uint256 _amount, address _receiver) external;

repay

function repay(address _poolToken, uint256 _amount) external;

repay

function repay(address _poolToken, address _onBehalf, uint256 _amount) external;

liquidate

function liquidate(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external;

IOracle

Git Source

Functions

consult

function consult(uint256 _amountIn) external returns (uint256);

Contents

Contents

ILens

Git Source

Functions

DEFAULT_LIQUIDATION_CLOSE_FACTOR

STORAGE ///

function DEFAULT_LIQUIDATION_CLOSE_FACTOR() external view returns (uint16);

HEALTH_FACTOR_LIQUIDATION_THRESHOLD

function HEALTH_FACTOR_LIQUIDATION_THRESHOLD() external view returns (uint256);

ST_ETH

function ST_ETH() external view returns (address);

ST_ETH_BASE_REBASE_INDEX

function ST_ETH_BASE_REBASE_INDEX() external view returns (uint256);

morpho

function morpho() external view returns (IMorpho);

addressesProvider

function addressesProvider() external view returns (ILendingPoolAddressesProvider);

pool

function pool() external view returns (ILendingPool);

getTotalSupply

GENERAL ///

function getTotalSupply()
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount, uint256 totalSupplyAmount);

getTotalBorrow

function getTotalBorrow()
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount, uint256 totalBorrowAmount);

isMarketCreated

MARKETS ///

function isMarketCreated(address _poolToken) external view returns (bool);

isMarketCreatedAndNotPaused

Deprecated.

function isMarketCreatedAndNotPaused(address _poolToken) external view returns (bool);

isMarketCreatedAndNotPausedNorPartiallyPaused

Deprecated.

function isMarketCreatedAndNotPausedNorPartiallyPaused(address _poolToken) external view returns (bool);

getAllMarkets

function getAllMarkets() external view returns (address[] memory marketsCreated_);

getMainMarketData

function getMainMarketData(address _poolToken)
    external
    view
    returns (
        uint256 avgSupplyRatePerYear,
        uint256 avgBorrowRatePerYear,
        uint256 p2pSupplyAmount,
        uint256 p2pBorrowAmount,
        uint256 poolSupplyAmount,
        uint256 poolBorrowAmount
    );

getAdvancedMarketData

function getAdvancedMarketData(address _poolToken)
    external
    view
    returns (Types.Indexes memory indexes, uint32 lastUpdateTimestamp, uint256 p2pSupplyDelta, uint256 p2pBorrowDelta);

getMarketConfiguration

function getMarketConfiguration(address _poolToken)
    external
    view
    returns (
        address underlying,
        bool isCreated,
        bool isP2PDisabled,
        bool isPaused,
        bool isPartiallyPaused,
        uint16 reserveFactor,
        uint16 p2pIndexCursor,
        uint256 loanToValue,
        uint256 liquidationThreshold,
        uint256 liquidationBonus,
        uint256 decimals
    );

getMarketPauseStatus

function getMarketPauseStatus(address _poolToken) external view returns (Types.MarketPauseStatus memory);

getTotalMarketSupply

function getTotalMarketSupply(address _poolToken)
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

getTotalMarketBorrow

function getTotalMarketBorrow(address _poolToken)
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

getCurrentP2PSupplyIndex

INDEXES ///

function getCurrentP2PSupplyIndex(address _poolToken) external view returns (uint256);

getCurrentP2PBorrowIndex

function getCurrentP2PBorrowIndex(address _poolToken) external view returns (uint256);

getIndexes

function getIndexes(address _poolToken) external view returns (Types.Indexes memory indexes);

getEnteredMarkets

USERS ///

function getEnteredMarkets(address _user) external view returns (address[] memory enteredMarkets);

getUserHealthFactor

function getUserHealthFactor(address _user) external view returns (uint256 healthFactor);

getUserBalanceStates

function getUserBalanceStates(address _user) external view returns (Types.LiquidityData memory assetData);

getCurrentSupplyBalanceInOf

function getCurrentSupplyBalanceInOf(address _poolToken, address _user)
    external
    view
    returns (uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

getCurrentBorrowBalanceInOf

function getCurrentBorrowBalanceInOf(address _poolToken, address _user)
    external
    view
    returns (uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

getUserMaxCapacitiesForAsset

function getUserMaxCapacitiesForAsset(address _user, address _poolToken)
    external
    view
    returns (uint256 withdrawable, uint256 borrowable);

getUserHypotheticalBalanceStates

function getUserHypotheticalBalanceStates(
    address _user,
    address _poolToken,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) external view returns (Types.LiquidityData memory assetData);

getUserHypotheticalHealthFactor

function getUserHypotheticalHealthFactor(
    address _user,
    address _poolToken,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) external view returns (uint256 healthFactor);

getUserLiquidityDataForAsset

function getUserLiquidityDataForAsset(address _user, address _poolToken, IPriceOracleGetter _oracle)
    external
    view
    returns (Types.AssetLiquidityData memory assetData);

isLiquidatable

function isLiquidatable(address _user) external view returns (bool);

isLiquidatable

function isLiquidatable(address _user, address _poolToken) external view returns (bool);

computeLiquidationRepayAmount

function computeLiquidationRepayAmount(address _user, address _poolTokenBorrowed, address _poolTokenCollateral)
    external
    view
    returns (uint256 toRepay);

getNextUserSupplyRatePerYear

RATES ///

function getNextUserSupplyRatePerYear(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextSupplyRatePerYear, uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

getNextUserBorrowRatePerYear

function getNextUserBorrowRatePerYear(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextBorrowRatePerYear, uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

getCurrentUserSupplyRatePerYear

function getCurrentUserSupplyRatePerYear(address _poolToken, address _user) external view returns (uint256);

getCurrentUserBorrowRatePerYear

function getCurrentUserBorrowRatePerYear(address _poolToken, address _user) external view returns (uint256);

getAverageSupplyRatePerYear

function getAverageSupplyRatePerYear(address _poolToken)
    external
    view
    returns (uint256 avgSupplyRatePerYear, uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

getAverageBorrowRatePerYear

function getAverageBorrowRatePerYear(address _poolToken)
    external
    view
    returns (uint256 avgBorrowRatePerYear, uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

getRatesPerYear

function getRatesPerYear(address _poolToken)
    external
    view
    returns (uint256 p2pSupplyRate, uint256 p2pBorrowRate, uint256 poolSupplyRate, uint256 poolBorrowRate);

IndexesLens

Git Source

Inherits: LensStorage

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol market indexes & rates.

Functions

getCurrentP2PSupplyIndex

EXTERNAL ///

Returns the updated peer-to-peer supply index.

function getCurrentP2PSupplyIndex(address _poolToken) external view returns (uint256 p2pSupplyIndex);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
p2pSupplyIndexuint256The updated peer-to-peer supply index.

getCurrentP2PBorrowIndex

Returns the updated peer-to-peer borrow index.

function getCurrentP2PBorrowIndex(address _poolToken) external view returns (uint256 p2pBorrowIndex);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
p2pBorrowIndexuint256The updated peer-to-peer borrow index.

getIndexes

Returns the updated peer-to-peer and pool indexes.

function getIndexes(address _poolToken) external view returns (Types.Indexes memory indexes);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
indexesTypes.IndexesThe given market's updated indexes.

_getIndexes

INTERNAL ///

Returns the updated peer-to-peer and pool indexes.

function _getIndexes(address _poolToken)
    internal
    view
    returns (Types.Market memory market, Types.Delta memory delta, Types.Indexes memory indexes);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
marketTypes.MarketThe given market's market data.
deltaTypes.DeltaThe given market's deltas.
indexesTypes.IndexesThe given market's updated indexes.

_getPoolIndexes

Returns the current pool indexes.

function _getPoolIndexes(address _underlyingToken)
    internal
    view
    returns (uint256 poolSupplyIndex, uint256 poolBorrowIndex);

Parameters

NameTypeDescription
_underlyingTokenaddressThe address of the underlying token.

Returns

NameTypeDescription
poolSupplyIndexuint256The pool supply index.
poolBorrowIndexuint256The pool borrow index.

Lens

Git Source

Inherits: MarketsLens

Author: Morpho Labs.

This contract exposes an API to query on-chain data related to the Morpho Protocol, its markets and its users.

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

constructor(address _morpho) LensStorage(_morpho);

Parameters

NameTypeDescription
_morphoaddressThe address of the main Morpho contract.

getTotalSupply

EXTERNAL ///

Computes and returns the total distribution of supply through Morpho, using virtually updated indexes.

function getTotalSupply()
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount, uint256 totalSupplyAmount);

Returns

NameTypeDescription
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in ETH).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in ETH).
totalSupplyAmountuint256The total amount supplied through Morpho (in ETH).

getTotalBorrow

Computes and returns the total distribution of borrows through Morpho, using virtually updated indexes.

function getTotalBorrow()
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount, uint256 totalBorrowAmount);

Returns

NameTypeDescription
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in ETH).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in ETH).
totalBorrowAmountuint256The total amount borrowed through Morpho (in ETH).

LensStorage

Git Source

Inherits: ILens

Author: Morpho Labs.

Base layer to the Morpho Protocol Lens, managing the upgradeable storage layout.

State Variables

DEFAULT_LIQUIDATION_CLOSE_FACTOR

CONSTANTS ///

uint16 public constant DEFAULT_LIQUIDATION_CLOSE_FACTOR = 50_00;

HEALTH_FACTOR_LIQUIDATION_THRESHOLD

uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;

ST_ETH

address public constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;

ST_ETH_BASE_REBASE_INDEX

IMMUTABLES ///

uint256 public immutable ST_ETH_BASE_REBASE_INDEX;

morpho

IMorpho public immutable morpho;

addressesProvider

ILendingPoolAddressesProvider public immutable addressesProvider;

pool

ILendingPool public immutable pool;

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

constructor(address _morpho);

Parameters

NameTypeDescription
_morphoaddressThe address of the main Morpho contract.

MarketsLens

Git Source

Inherits: RatesLens

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol markets.

Functions

isMarketCreated

EXTERNAL ///

Checks if a market is created.

function isMarketCreated(address _poolToken) external view returns (bool);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
<none>booltrue if the market is created and not paused, otherwise false.

isMarketCreatedAndNotPaused

Deprecated.

function isMarketCreatedAndNotPaused(address) external pure returns (bool);

isMarketCreatedAndNotPausedNorPartiallyPaused

Deprecated.

function isMarketCreatedAndNotPausedNorPartiallyPaused(address) external pure returns (bool);

getAllMarkets

Returns all created markets.

function getAllMarkets() external view returns (address[] memory marketsCreated);

Returns

NameTypeDescription
marketsCreatedaddress[]The list of market addresses.

getMainMarketData

For a given market, returns the average supply/borrow rates and amounts of underlying asset supplied and borrowed through Morpho, on the underlying pool and matched peer-to-peer.

The returned values are not updated.

function getMainMarketData(address _poolToken)
    external
    view
    returns (
        uint256 avgSupplyRatePerYear,
        uint256 avgBorrowRatePerYear,
        uint256 p2pSupplyAmount,
        uint256 p2pBorrowAmount,
        uint256 poolSupplyAmount,
        uint256 poolBorrowAmount
    );

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get main data.

Returns

NameTypeDescription
avgSupplyRatePerYearuint256The average supply rate experienced on the given market.
avgBorrowRatePerYearuint256The average borrow rate experienced on the given market.
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

getAdvancedMarketData

Returns non-updated indexes, the block at which they were last updated and the total deltas of a given market.

function getAdvancedMarketData(address _poolToken)
    external
    view
    returns (Types.Indexes memory indexes, uint32 lastUpdateTimestamp, uint256 p2pSupplyDelta, uint256 p2pBorrowDelta);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get advanced data.

Returns

NameTypeDescription
indexesTypes.IndexesThe given market's updated indexes.
lastUpdateTimestampuint32The timestamp of the block at which pool indexes were last updated.
p2pSupplyDeltauint256The total supply delta (in underlying).
p2pBorrowDeltauint256The total borrow delta (in underlying).

getMarketConfiguration

Returns the given market's configuration.

function getMarketConfiguration(address _poolToken)
    external
    view
    returns (
        address underlying,
        bool isCreated,
        bool isP2PDisabled,
        bool isPaused,
        bool isPartiallyPaused,
        uint16 reserveFactor,
        uint16 p2pIndexCursor,
        uint256 loanToValue,
        uint256 liquidationThreshold,
        uint256 liquidationBonus,
        uint256 decimals
    );

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get the configuration.

Returns

NameTypeDescription
underlyingaddressThe underlying token address.
isCreatedboolWhether the market is created or not.
isP2PDisabledboolWhether the peer-to-peer market is enabled or not.
isPausedboolDeprecated.
isPartiallyPausedboolDeprecated.
reserveFactoruint16The reserve factor applied to this market.
p2pIndexCursoruint16The p2p index cursor applied to this market.
loanToValueuint256The ltv of the given market, set by AAVE.
liquidationThresholduint256The liquidation threshold of the given market, set by AAVE.
liquidationBonusuint256The liquidation bonus of the given market, set by AAVE.
decimalsuint256The number of decimals of the underlying token.

getMarketPauseStatus

Returns the given market's pause statuses.

function getMarketPauseStatus(address _poolToken) external view returns (Types.MarketPauseStatus memory);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get pause statuses.

Returns

NameTypeDescription
<none>Types.MarketPauseStatusThe market status struct.

getTotalMarketSupply

Computes and returns the total distribution of supply for a given market, using virtually updated indexes.

function getTotalMarketSupply(address _poolToken)
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

getTotalMarketBorrow

Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.

function getTotalMarketBorrow(address _poolToken)
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

_getTotalMarketSupply

INTERNAL ///

Computes and returns the total distribution of supply for a given market, using virtually updated indexes.

function _getTotalMarketSupply(address _poolToken)
    internal
    view
    returns (address underlyingToken, uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
underlyingTokenaddressThe address of the underlying ERC20 token of the given market.
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

_getTotalMarketBorrow

Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.

function _getTotalMarketBorrow(address _poolToken)
    internal
    view
    returns (address underlyingToken, uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
underlyingTokenaddressThe address of the underlying ERC20 token of the given market.
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

RatesLens

Git Source

Inherits: UsersLens

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol users and their positions.

Functions

getNextUserSupplyRatePerYear

EXTERNAL ///

Returns the supply rate per year experienced on a market after having supplied the given amount on behalf of the given user.

Note: the returned supply rate is a low estimate: when supplying through Morpho-Aave, a supplier could be matched more than once instantly or later and thus benefit from a higher supply rate.

function getNextUserSupplyRatePerYear(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextSupplyRatePerYear, uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe address of the user on behalf of whom to supply.
_amountuint256The amount to supply.

Returns

NameTypeDescription
nextSupplyRatePerYearuint256An approximation of the next supply rate per year experienced after having supplied (in ray).
balanceInP2Puint256The total balance matched peer-to-peer after having supplied (in underlying).
balanceOnPooluint256The total balance supplied on pool after having supplied (in underlying).
totalBalanceuint256The total balance supplied through Morpho (in underlying).

getNextUserBorrowRatePerYear

Returns the borrow rate per year experienced on a market after having supplied the given amount on behalf of the given user.

Note: the returned borrow rate is a high estimate: when borrowing through Morpho-Aave, a borrower could be matched more than once instantly or later and thus benefit from a lower borrow rate.

function getNextUserBorrowRatePerYear(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextBorrowRatePerYear, uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe address of the user on behalf of whom to borrow.
_amountuint256The amount to borrow.

Returns

NameTypeDescription
nextBorrowRatePerYearuint256An approximation of the next borrow rate per year experienced after having supplied (in ray).
balanceInP2Puint256The total balance matched peer-to-peer after having supplied (in underlying).
balanceOnPooluint256The total balance supplied on pool after having supplied (in underlying).
totalBalanceuint256The total balance supplied through Morpho (in underlying).

getCurrentUserSupplyRatePerYear

Returns the supply rate per year a given user is currently experiencing on a given market.

function getCurrentUserSupplyRatePerYear(address _poolToken, address _user)
    external
    view
    returns (uint256 supplyRatePerYear);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to compute the supply rate per year for.

Returns

NameTypeDescription
supplyRatePerYearuint256The supply rate per year the user is currently experiencing (in wad).

getCurrentUserBorrowRatePerYear

Returns the borrow rate per year a given user is currently experiencing on a given market.

function getCurrentUserBorrowRatePerYear(address _poolToken, address _user)
    external
    view
    returns (uint256 borrowRatePerYear);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to compute the borrow rate per year for.

Returns

NameTypeDescription
borrowRatePerYearuint256The borrow rate per year the user is currently experiencing (in wad).

getAverageSupplyRatePerYear

PUBLIC ///

Computes and returns the current supply rate per year experienced on average on a given market.

function getAverageSupplyRatePerYear(address _poolToken)
    public
    view
    returns (uint256 avgSupplyRatePerYear, uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.

Returns

NameTypeDescription
avgSupplyRatePerYearuint256The market's average supply rate per year (in ray).
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

getAverageBorrowRatePerYear

Computes and returns the current average borrow rate per year experienced on a given market.

function getAverageBorrowRatePerYear(address _poolToken)
    public
    view
    returns (uint256 avgBorrowRatePerYear, uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.

Returns

NameTypeDescription
avgBorrowRatePerYearuint256The market's average borrow rate per year (in ray).
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

getRatesPerYear

Computes and returns peer-to-peer and pool rates for a specific market.

Note: prefer using getAverageSupplyRatePerYear & getAverageBorrowRatePerYear to get the actual experienced supply/borrow rate.

function getRatesPerYear(address _poolToken) public view returns (uint256, uint256, uint256, uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.

Returns

NameTypeDescription
<none>uint256p2pSupplyRate The market's peer-to-peer supply rate per year (in ray).
<none>uint256p2pBorrowRate The market's peer-to-peer borrow rate per year (in ray).
<none>uint256poolSupplyRate The market's pool supply rate per year (in ray).
<none>uint256poolBorrowRate The market's pool borrow rate per year (in ray).

_getRatesPerYear

INTERNAL ///

Computes and returns peer-to-peer and pool rates for a specific market.

function _getRatesPerYear(
    address _poolToken,
    uint256 _suppliedOnPool,
    uint256 _borrowedFromPool,
    uint256 _withdrawnFromPool,
    uint256 _repaidOnPool
)
    internal
    view
    returns (uint256 p2pSupplyRate, uint256 p2pBorrowRate, uint256 poolSupplyRate, uint256 poolBorrowRate);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.
_suppliedOnPooluint256The amount hypothetically supplied to the underlying's pool (in underlying).
_borrowedFromPooluint256The amount hypothetically borrowed from the underlying's pool (in underlying).
_withdrawnFromPooluint256The amount hypothetically withdrawn from the underlying's pool (in underlying).
_repaidOnPooluint256The amount hypothetically repaid to the underlying's pool (in underlying).

Returns

NameTypeDescription
p2pSupplyRateuint256The market's peer-to-peer supply rate per year (in ray).
p2pBorrowRateuint256The market's peer-to-peer borrow rate per year (in ray).
poolSupplyRateuint256The market's pool supply rate per year (in ray).
poolBorrowRateuint256The market's pool borrow rate per year (in ray).

_getPoolRatesPerYear

Computes and returns the underlying pool rates for a specific market.

function _getPoolRatesPerYear(
    address _underlying,
    uint256 _supplied,
    uint256 _borrowed,
    uint256 _withdrawn,
    uint256 _repaid
) internal view returns (uint256 poolSupplyRate, uint256 poolBorrowRate);

Parameters

NameTypeDescription
_underlyingaddressThe underlying pool market address.
_supplieduint256The amount hypothetically supplied (in underlying).
_borroweduint256The amount hypothetically borrowed (in underlying).
_withdrawnuint256The amount hypothetically withdrawn (in underlying).
_repaiduint256The amount hypothetically repaid (in underlying).

Returns

NameTypeDescription
poolSupplyRateuint256The market's pool supply rate per year (in ray).
poolBorrowRateuint256The market's pool borrow rate per year (in ray).

_getMarketSupply

Computes and returns the total distribution of supply for a given market, using virtually updated indexes.

function _getMarketSupply(
    address _poolToken,
    uint256 _p2pSupplyIndex,
    uint256 _poolSupplyIndex,
    Types.Delta memory _delta
) internal view returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.
_p2pSupplyIndexuint256The given market's peer-to-peer supply index.
_poolSupplyIndexuint256The given market's pool supply index.
_deltaTypes.DeltaThe given market's deltas.

Returns

NameTypeDescription
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

_getMarketBorrow

Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.

function _getMarketBorrow(
    DataTypes.ReserveData memory reserve,
    uint256 _p2pBorrowIndex,
    uint256 _poolBorrowIndex,
    Types.Delta memory _delta
) internal view returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
reserveDataTypes.ReserveDataThe reserve data of the underlying pool.
_p2pBorrowIndexuint256The given market's peer-to-peer borrow index.
_poolBorrowIndexuint256The given market's pool borrow index.
_deltaTypes.DeltaThe given market's deltas.

Returns

NameTypeDescription
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

_getUserSupplyRatePerYear

Returns the supply rate per year experienced on a market based on a given position distribution. The calculation takes into account the change in pool rates implied by an hypothetical supply and/or repay.

function _getUserSupplyRatePerYear(
    address _poolToken,
    uint256 _balanceInP2P,
    uint256 _balanceOnPool,
    uint256 _suppliedOnPool,
    uint256 _repaidToPool
) internal view returns (uint256, uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_balanceInP2Puint256The amount of balance matched peer-to-peer (in a unit common to _balanceOnPool).
_balanceOnPooluint256The amount of balance supplied on pool (in a unit common to _balanceInP2P).
_suppliedOnPooluint256The amount hypothetically supplied on pool (in underlying).
_repaidToPooluint256The amount hypothetically repaid to the pool (in underlying).

Returns

NameTypeDescription
<none>uint256The supply rate per year experienced by the given position (in ray).
<none>uint256The sum of peer-to-peer & pool balances.

_getUserBorrowRatePerYear

Returns the borrow rate per year experienced on a market based on a given position distribution. The calculation takes into account the change in pool rates implied by an hypothetical borrow and/or withdraw.

function _getUserBorrowRatePerYear(
    address _poolToken,
    uint256 _balanceInP2P,
    uint256 _balanceOnPool,
    uint256 _borrowedFromPool,
    uint256 _withdrawnFromPool
) internal view returns (uint256, uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_balanceInP2Puint256The amount of balance matched peer-to-peer (in a unit common to _balanceOnPool).
_balanceOnPooluint256The amount of balance supplied on pool (in a unit common to _balanceInP2P).
_borrowedFromPooluint256The amount hypothetically borrowed from the pool (in underlying).
_withdrawnFromPooluint256The amount hypothetically withdrawn from the pool (in underlying).

Returns

NameTypeDescription
<none>uint256The borrow rate per year experienced by the given position (in ray).
<none>uint256The sum of peer-to-peer & pool balances.

_getWeightedRate

Returns the rate experienced based on a given pool & peer-to-peer distribution.

function _getWeightedRate(uint256 _p2pRate, uint256 _poolRate, uint256 _balanceInP2P, uint256 _balanceOnPool)
    internal
    pure
    returns (uint256 weightedRate, uint256 totalBalance);

Parameters

NameTypeDescription
_p2pRateuint256The peer-to-peer rate (in a unit common to _poolRate & weightedRate).
_poolRateuint256The pool rate (in a unit common to _p2pRate & weightedRate).
_balanceInP2Puint256The amount of balance matched peer-to-peer (in a unit common to _balanceOnPool).
_balanceOnPooluint256The amount of balance supplied on pool (in a unit common to _balanceInP2P).

Returns

NameTypeDescription
weightedRateuint256The rate experienced by the given distribution (in a unit common to _p2pRate & _poolRate).
totalBalanceuint256The sum of peer-to-peer & pool balances.

UsersLens

Git Source

Inherits: IndexesLens

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol users and their positions.

Functions

getEnteredMarkets

EXTERNAL ///

Returns all markets entered by a given user.

function getEnteredMarkets(address _user) external view returns (address[] memory enteredMarkets);

Parameters

NameTypeDescription
_useraddressThe address of the user.

Returns

NameTypeDescription
enteredMarketsaddress[]The list of markets entered by this user.

getUserMaxCapacitiesForAsset

Returns the maximum amount available to withdraw & borrow for a given user, on a given market.

function getUserMaxCapacitiesForAsset(address _user, address _poolToken)
    external
    view
    returns (uint256 withdrawable, uint256 borrowable);

Parameters

NameTypeDescription
_useraddressThe user to determine the capacities for.
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
withdrawableuint256The maximum withdrawable amount of underlying token allowed (in underlying).
borrowableuint256The maximum borrowable amount of underlying token allowed (in underlying).

computeLiquidationRepayAmount

Computes the maximum repayable amount for a potential liquidation.

function computeLiquidationRepayAmount(address _user, address _poolTokenBorrowed, address _poolTokenCollateral)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
_useraddressThe potential liquidatee.
_poolTokenBorrowedaddressThe address of the market to repay.
_poolTokenCollateraladdressThe address of the market to seize.

Returns

NameTypeDescription
<none>uint256The maximum repayable amount (in underlying).

getCurrentSupplyBalanceInOf

Returns the balance in underlying of a given user in a given market.

function getCurrentSupplyBalanceInOf(address _poolToken, address _user)
    external
    view
    returns (uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to determine balances of.

Returns

NameTypeDescription
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
balanceOnPooluint256The balance on pool of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

getCurrentBorrowBalanceInOf

Returns the borrow balance in underlying of a given user in a given market.

function getCurrentBorrowBalanceInOf(address _poolToken, address _user)
    external
    view
    returns (uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to determine balances of.

Returns

NameTypeDescription
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
balanceOnPooluint256The balance on pool of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

getUserBalanceStates

PUBLIC ///

Returns the collateral value, debt value and max debt value of a given user.

function getUserBalanceStates(address _user) public view returns (Types.LiquidityData memory);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.

Returns

NameTypeDescription
<none>Types.LiquidityDataThe liquidity data of the user.

getUserHypotheticalBalanceStates

Returns the aggregated position of a given user, following an hypothetical borrow/withdraw on a given market, using virtually updated pool & peer-to-peer indexes for all markets.

function getUserHypotheticalBalanceStates(
    address _user,
    address _poolToken,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) public view returns (Types.LiquidityData memory liquidityData);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_poolTokenaddressThe market to hypothetically withdraw/borrow in.
_withdrawnAmountuint256The number of tokens to hypothetically withdraw from the given market (in underlying).
_borrowedAmountuint256The amount of tokens to hypothetically borrow from the given market (in underlying).

Returns

NameTypeDescription
liquidityDataTypes.LiquidityDataThe liquidity data of the user.

getUserLiquidityDataForAsset

Returns the data related to _poolToken for the _user.

function getUserLiquidityDataForAsset(address _user, address _poolToken, IPriceOracleGetter _oracle)
    public
    view
    returns (Types.AssetLiquidityData memory);

Parameters

NameTypeDescription
_useraddressThe user to determine data for.
_poolTokenaddressThe address of the market.
_oracleIPriceOracleGetterThe oracle used.

Returns

NameTypeDescription
<none>Types.AssetLiquidityDataassetData The data related to this asset.

getUserHealthFactor

Returns the health factor of a given user, using virtually updated pool & peer-to-peer indexes for all markets.

function getUserHealthFactor(address _user) public view returns (uint256);

Parameters

NameTypeDescription
_useraddressThe user of whom to get the health factor.

Returns

NameTypeDescription
<none>uint256The health factor of the given user (in wad).

getUserHypotheticalHealthFactor

Returns the hypothetical health factor of a user, following an hypothetical borrow/withdraw on a given market, using virtually updated pool & peer-to-peer indexes for all markets.

function getUserHypotheticalHealthFactor(
    address _user,
    address _poolToken,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) public view returns (uint256 healthFactor);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_poolTokenaddressThe market to hypothetically withdraw/borrow from.
_withdrawnAmountuint256The number of tokens to hypothetically withdraw (in underlying).
_borrowedAmountuint256The amount of tokens to hypothetically borrow (in underlying).

Returns

NameTypeDescription
healthFactoruint256The health factor of the user.

isLiquidatable

Returns whether a liquidation can be performed on a given user, based on their health factor.

This function checks for the user's health factor, without treating borrow positions from deprecated market as instantly liquidatable.

function isLiquidatable(address _user) public view returns (bool);

Parameters

NameTypeDescription
_useraddressThe address of the user to check.

Returns

NameTypeDescription
<none>boolwhether or not the user is liquidatable.

isLiquidatable

Returns whether a liquidation can be performed on a given user borrowing from a given market.

This function checks for the user's health factor as well as whether the given market is deprecated & the user is borrowing from it.

function isLiquidatable(address _user, address _poolToken) public view returns (bool);

Parameters

NameTypeDescription
_useraddressThe address of the user to check.
_poolTokenaddressThe address of the borrowed market to check.

Returns

NameTypeDescription
<none>boolwhether or not the user is liquidatable.

_isBorrowing

INTERNAL ///

Returns wheter the given user is borrowing from the given market.

function _isBorrowing(address _user, address _market) internal view returns (bool);

Parameters

NameTypeDescription
_useraddressThe address of the user to check.
_marketaddressThe address of the market to check.

Returns

NameTypeDescription
<none>boolTrue if the user has been supplying or borrowing on this market, false otherwise.

_isSupplyingOrBorrowing

Returns whether the given user is borrowing or supplying on the given market.

function _isSupplyingOrBorrowing(bytes32 _userMarkets, address _market) internal view returns (bool);

Parameters

NameTypeDescription
_userMarketsbytes32The bytes representation of entered markets of the user to check for.
_marketaddressThe address of the market to check.

Returns

NameTypeDescription
<none>boolTrue if the user has been supplying or borrowing on this market, false otherwise.

_getCurrentSupplyBalanceInOf

Returns the balance in underlying of a given user in a given market.

function _getCurrentSupplyBalanceInOf(address _poolToken, address _user)
    internal
    view
    returns (address underlyingToken, uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to determine balances of.

Returns

NameTypeDescription
underlyingTokenaddressThe address of the underlying ERC20 token of the given market.
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
balanceOnPooluint256The balance on pool of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

_getCurrentBorrowBalanceInOf

Returns the borrow balance in underlying of a given user in a given market.

function _getCurrentBorrowBalanceInOf(address _poolToken, address _user)
    internal
    view
    returns (address underlyingToken, uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to determine balances of.

Returns

NameTypeDescription
underlyingTokenaddressThe address of the underlying ERC20 token of the given market.
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
balanceOnPooluint256The balance on pool of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

_getSupplyBalanceInOf

Returns the supply balance of _user in the _poolToken market.

Note: Computes the result with the stored indexes, which are not always the most up to date ones.

function _getSupplyBalanceInOf(address _poolToken, address _user, uint256 _p2pSupplyIndex, uint256 _poolSupplyIndex)
    internal
    view
    returns (uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the supply amount.
_useraddressThe address of the user.
_p2pSupplyIndexuint256The peer-to-peer supply index of the given market (in ray).
_poolSupplyIndexuint256The pool supply index of the given market (in ray).

Returns

NameTypeDescription
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
balanceOnPooluint256The balance on pool of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

_getBorrowBalanceInOf

Returns the borrow balance of _user in the _poolToken market.

function _getBorrowBalanceInOf(address _poolToken, address _user, uint256 _p2pBorrowIndex, uint256 _poolBorrowIndex)
    internal
    view
    returns (uint256 balanceInP2P, uint256 balanceOnPool, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the borrow amount.
_useraddressThe address of the user.
_p2pBorrowIndexuint256The peer-to-peer borrow index of the given market (in ray).
_poolBorrowIndexuint256The pool borrow index of the given market (in ray).

Returns

NameTypeDescription
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
balanceOnPooluint256The balance on pool of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

_getUserHypotheticalLiquidityDataForAsset

Returns the data related to _poolToken for the _user.

function _getUserHypotheticalLiquidityDataForAsset(
    address _user,
    address _poolToken,
    IPriceOracleGetter _oracle,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) internal view returns (Types.AssetLiquidityData memory assetData);

Parameters

NameTypeDescription
_useraddressThe user to determine data for.
_poolTokenaddressThe address of the market.
_oracleIPriceOracleGetterThe oracle used.
_withdrawnAmountuint256The amount to hypothetically withdraw from the given market (in underlying).
_borrowedAmountuint256The amount to hypothetically borrow from the given market (in underlying).

Returns

NameTypeDescription
assetDataTypes.AssetLiquidityDataThe data related to this asset.

Contents

Contents

DataTypes

Git Source

Structs

ReserveData

struct ReserveData {
    ReserveConfigurationMap configuration;
    uint128 liquidityIndex;
    uint128 variableBorrowIndex;
    uint128 currentLiquidityRate;
    uint128 currentVariableBorrowRate;
    uint128 currentStableBorrowRate;
    uint40 lastUpdateTimestamp;
    address aTokenAddress;
    address stableDebtTokenAddress;
    address variableDebtTokenAddress;
    address interestRateStrategyAddress;
    uint8 id;
}

ReserveConfigurationMap

struct ReserveConfigurationMap {
    uint256 data;
}

UserConfigurationMap

struct UserConfigurationMap {
    uint256 data;
}

Enums

InterestRateMode

enum InterestRateMode {
    NONE,
    STABLE,
    VARIABLE
}

Errors

Git Source

Author: Aave

Defines the error messages emitted by the different contracts of the Aave protocol

*Error messages prefix glossary:

  • VL = ValidationLogic
  • MATH = Math libraries
  • CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken)
  • AT = AToken
  • SDT = StableDebtToken
  • VDT = VariableDebtToken
  • LP = LendingPool
  • LPAPR = LendingPoolAddressesProviderRegistry
  • LPC = LendingPoolConfiguration
  • RL = ReserveLogic
  • LPCM = LendingPoolCollateralManager
  • P = Pausable*

State Variables

CALLER_NOT_POOL_ADMIN

string public constant CALLER_NOT_POOL_ADMIN = "33";

BORROW_ALLOWANCE_NOT_ENOUGH

string public constant BORROW_ALLOWANCE_NOT_ENOUGH = "59";

VL_INVALID_AMOUNT

string public constant VL_INVALID_AMOUNT = "1";

VL_NO_ACTIVE_RESERVE

string public constant VL_NO_ACTIVE_RESERVE = "2";

VL_RESERVE_FROZEN

string public constant VL_RESERVE_FROZEN = "3";

VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH

string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = "4";

VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE

string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "5";

VL_TRANSFER_NOT_ALLOWED

string public constant VL_TRANSFER_NOT_ALLOWED = "6";

VL_BORROWING_NOT_ENABLED

string public constant VL_BORROWING_NOT_ENABLED = "7";

VL_INVALID_INTEREST_RATE_MODE_SELECTED

string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = "8";

VL_COLLATERAL_BALANCE_IS_0

string public constant VL_COLLATERAL_BALANCE_IS_0 = "9";

VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD

string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "10";

VL_COLLATERAL_CANNOT_COVER_NEW_BORROW

string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "11";

VL_STABLE_BORROWING_NOT_ENABLED

string public constant VL_STABLE_BORROWING_NOT_ENABLED = "12";

VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY

string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = "13";

VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE

string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = "14";

VL_NO_DEBT_OF_SELECTED_TYPE

string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "15";

VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF

string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = "16";

VL_NO_STABLE_RATE_LOAN_IN_RESERVE

string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = "17";

VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE

string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = "18";

VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0

string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = "19";

VL_DEPOSIT_ALREADY_IN_USE

string public constant VL_DEPOSIT_ALREADY_IN_USE = "20";

LP_NOT_ENOUGH_STABLE_BORROW_BALANCE

string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = "21";

LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET

string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = "22";

LP_LIQUIDATION_CALL_FAILED

string public constant LP_LIQUIDATION_CALL_FAILED = "23";

LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW

string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = "24";

LP_REQUESTED_AMOUNT_TOO_SMALL

string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = "25";

LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE

string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = "26";

LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR

string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = "27";

LP_INCONSISTENT_FLASHLOAN_PARAMS

string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = "28";

CT_CALLER_MUST_BE_LENDING_POOL

string public constant CT_CALLER_MUST_BE_LENDING_POOL = "29";

CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF

string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = "30";

CT_TRANSFER_AMOUNT_NOT_GT_0

string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = "31";

RL_RESERVE_ALREADY_INITIALIZED

string public constant RL_RESERVE_ALREADY_INITIALIZED = "32";

LPC_RESERVE_LIQUIDITY_NOT_0

string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "34";

LPC_INVALID_ATOKEN_POOL_ADDRESS

string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = "35";

LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS

string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = "36";

LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS

string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = "37";

LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS

string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = "38";

LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS

string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = "39";

LPC_INVALID_ADDRESSES_PROVIDER_ID

string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = "40";

LPC_INVALID_CONFIGURATION

string public constant LPC_INVALID_CONFIGURATION = "75";

LPC_CALLER_NOT_EMERGENCY_ADMIN

string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "76";

LPAPR_PROVIDER_NOT_REGISTERED

string public constant LPAPR_PROVIDER_NOT_REGISTERED = "41";

LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD

string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = "42";

LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED

string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = "43";

LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER

string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "44";

LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE

string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = "45";

LPCM_NO_ERRORS

string public constant LPCM_NO_ERRORS = "46";

LP_INVALID_FLASHLOAN_MODE

string public constant LP_INVALID_FLASHLOAN_MODE = "47";

MATH_MULTIPLICATION_OVERFLOW

string public constant MATH_MULTIPLICATION_OVERFLOW = "48";

MATH_ADDITION_OVERFLOW

string public constant MATH_ADDITION_OVERFLOW = "49";

MATH_DIVISION_BY_ZERO

string public constant MATH_DIVISION_BY_ZERO = "50";

RL_LIQUIDITY_INDEX_OVERFLOW

string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "51";

RL_VARIABLE_BORROW_INDEX_OVERFLOW

string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "52";

RL_LIQUIDITY_RATE_OVERFLOW

string public constant RL_LIQUIDITY_RATE_OVERFLOW = "53";

RL_VARIABLE_BORROW_RATE_OVERFLOW

string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "54";

RL_STABLE_BORROW_RATE_OVERFLOW

string public constant RL_STABLE_BORROW_RATE_OVERFLOW = "55";

CT_INVALID_MINT_AMOUNT

string public constant CT_INVALID_MINT_AMOUNT = "56";

LP_FAILED_REPAY_WITH_COLLATERAL

string public constant LP_FAILED_REPAY_WITH_COLLATERAL = "57";

CT_INVALID_BURN_AMOUNT

string public constant CT_INVALID_BURN_AMOUNT = "58";

LP_FAILED_COLLATERAL_SWAP

string public constant LP_FAILED_COLLATERAL_SWAP = "60";

LP_INVALID_EQUAL_ASSETS_TO_SWAP

string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = "61";

LP_REENTRANCY_NOT_ALLOWED

string public constant LP_REENTRANCY_NOT_ALLOWED = "62";

LP_CALLER_MUST_BE_AN_ATOKEN

string public constant LP_CALLER_MUST_BE_AN_ATOKEN = "63";

LP_IS_PAUSED

string public constant LP_IS_PAUSED = "64";

LP_NO_MORE_RESERVES_ALLOWED

string public constant LP_NO_MORE_RESERVES_ALLOWED = "65";

LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN

string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = "66";

RC_INVALID_LTV

string public constant RC_INVALID_LTV = "67";

RC_INVALID_LIQ_THRESHOLD

string public constant RC_INVALID_LIQ_THRESHOLD = "68";

RC_INVALID_LIQ_BONUS

string public constant RC_INVALID_LIQ_BONUS = "69";

RC_INVALID_DECIMALS

string public constant RC_INVALID_DECIMALS = "70";

RC_INVALID_RESERVE_FACTOR

string public constant RC_INVALID_RESERVE_FACTOR = "71";

LPAPR_INVALID_ADDRESSES_PROVIDER_ID

string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "72";

VL_INCONSISTENT_FLASHLOAN_PARAMS

string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = "73";

LP_INCONSISTENT_PARAMS_LENGTH

string public constant LP_INCONSISTENT_PARAMS_LENGTH = "74";

UL_INVALID_INDEX

string public constant UL_INVALID_INDEX = "77";

LP_NOT_CONTRACT

string public constant LP_NOT_CONTRACT = "78";

SDT_STABLE_DEBT_OVERFLOW

string public constant SDT_STABLE_DEBT_OVERFLOW = "79";

SDT_BURN_EXCEEDS_BALANCE

string public constant SDT_BURN_EXCEEDS_BALANCE = "80";

Enums

CollateralManagerErrors

enum CollateralManagerErrors {
    NO_ERROR,
    NO_COLLATERAL_AVAILABLE,
    COLLATERAL_CANNOT_BE_LIQUIDATED,
    CURRRENCY_NOT_BORROWED,
    HEALTH_FACTOR_ABOVE_THRESHOLD,
    NOT_ENOUGH_LIQUIDITY,
    NO_ACTIVE_RESERVE,
    HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,
    INVALID_EQUAL_ASSETS_TO_SWAP,
    FROZEN_RESERVE
}

ReserveConfiguration

Git Source

Author: Aave

Implements the bitmap logic to handle the reserve configuration

State Variables

LTV_MASK

uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000;

LIQUIDATION_THRESHOLD_MASK

uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF;

LIQUIDATION_BONUS_MASK

uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF;

DECIMALS_MASK

uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF;

ACTIVE_MASK

uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF;

FROZEN_MASK

uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF;

BORROWING_MASK

uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF;

STABLE_BORROWING_MASK

uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF;

RESERVE_FACTOR_MASK

uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF;

LIQUIDATION_THRESHOLD_START_BIT_POSITION

For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed

uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;

LIQUIDATION_BONUS_START_BIT_POSITION

uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;

RESERVE_DECIMALS_START_BIT_POSITION

uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;

IS_ACTIVE_START_BIT_POSITION

uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;

IS_FROZEN_START_BIT_POSITION

uint256 constant IS_FROZEN_START_BIT_POSITION = 57;

BORROWING_ENABLED_START_BIT_POSITION

uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;

STABLE_BORROWING_ENABLED_START_BIT_POSITION

uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;

RESERVE_FACTOR_START_BIT_POSITION

uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;

MAX_VALID_LTV

uint256 constant MAX_VALID_LTV = 65535;

MAX_VALID_LIQUIDATION_THRESHOLD

uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;

MAX_VALID_LIQUIDATION_BONUS

uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;

MAX_VALID_DECIMALS

uint256 constant MAX_VALID_DECIMALS = 255;

MAX_VALID_RESERVE_FACTOR

uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;

Functions

setLtv

Sets the Loan to Value of the reserve

function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
ltvuint256the new ltv

getLtv

Gets the Loan to Value of the reserve

function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The loan to value

setLiquidationThreshold

Sets the liquidation threshold of the reserve

function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
thresholduint256The new liquidation threshold

getLiquidationThreshold

Gets the liquidation threshold of the reserve

function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The liquidation threshold

setLiquidationBonus

Sets the liquidation bonus of the reserve

function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
bonusuint256The new liquidation bonus

getLiquidationBonus

Gets the liquidation bonus of the reserve

function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The liquidation bonus

setDecimals

Sets the decimals of the underlying asset of the reserve

function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
decimalsuint256The decimals

getDecimals

Gets the decimals of the underlying asset of the reserve

function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The decimals of the asset

setActive

Sets the active state of the reserve

function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
activeboolThe active state

getActive

Gets the active state of the reserve

function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>boolThe active state

setFrozen

Sets the frozen state of the reserve

function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
frozenboolThe frozen state

getFrozen

Gets the frozen state of the reserve

function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>boolThe frozen state

setBorrowingEnabled

Enables or disables borrowing on the reserve

function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
enabledboolTrue if the borrowing needs to be enabled, false otherwise

getBorrowingEnabled

Gets the borrowing state of the reserve

function getBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>boolThe borrowing state

setStableRateBorrowingEnabled

Enables or disables stable rate borrowing on the reserve

function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
enabledboolTrue if the stable rate borrowing needs to be enabled, false otherwise

getStableRateBorrowingEnabled

Gets the stable rate borrowing state of the reserve

function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>boolThe stable rate borrowing state

setReserveFactor

Sets the reserve factor of the reserve

function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure;

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration
reserveFactoruint256The reserve factor

getReserveFactor

Gets the reserve factor of the reserve

function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The reserve factor

getFlags

Gets the configuration flags of the reserve

function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool, bool, bool, bool);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>boolThe state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
<none>bool
<none>bool
<none>bool

getParams

Gets the configuration paramters of the reserve

function getParams(DataTypes.ReserveConfigurationMap storage self)
    internal
    view
    returns (uint256, uint256, uint256, uint256, uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
<none>uint256
<none>uint256
<none>uint256
<none>uint256

getParamsMemory

Gets the configuration paramters of the reserve from a memory object

function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
    internal
    pure
    returns (uint256, uint256, uint256, uint256, uint256);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>uint256The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
<none>uint256
<none>uint256
<none>uint256
<none>uint256

getFlagsMemory

Gets the configuration flags of the reserve from a memory object

function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool, bool, bool, bool);

Parameters

NameTypeDescription
selfDataTypes.ReserveConfigurationMapThe reserve configuration

Returns

NameTypeDescription
<none>boolThe state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
<none>bool
<none>bool
<none>bool

UserConfiguration

Git Source

Functions

isUsingAsCollateral

function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
    internal
    pure
    returns (bool);

InterestRatesModel

Git Source

Functions

computeGrowthFactors

Computes and returns the new supply/borrow growth factors associated to the given market's pool & peer-to-peer indexes.

function computeGrowthFactors(
    uint256 _newPoolSupplyIndex,
    uint256 _newPoolBorrowIndex,
    Types.PoolIndexes memory _lastPoolIndexes,
    uint256 _p2pIndexCursor,
    uint256 _reserveFactor
) internal pure returns (GrowthFactors memory growthFactors);

Parameters

NameTypeDescription
_newPoolSupplyIndexuint256The current pool supply index.
_newPoolBorrowIndexuint256The current pool borrow index.
_lastPoolIndexesTypes.PoolIndexesThe last stored pool indexes.
_p2pIndexCursoruint256The peer-to-peer index cursor for the given market.
_reserveFactoruint256The reserve factor of the given market.

Returns

NameTypeDescription
growthFactorsGrowthFactorsThe market's indexes growth factors (in ray).

computeP2PIndex

Computes and returns the new peer-to-peer supply/borrow index of a market given its parameters.

function computeP2PIndex(P2PIndexComputeParams memory _params) internal pure returns (uint256 newP2PIndex);

Parameters

NameTypeDescription
_paramsP2PIndexComputeParamsThe computation parameters.

Returns

NameTypeDescription
newP2PIndexuint256The updated peer-to-peer index (in ray).

computeP2PSupplyRatePerYear

Computes and returns the peer-to-peer supply rate per year of a market given its parameters.

function computeP2PSupplyRatePerYear(P2PRateComputeParams memory _params)
    internal
    pure
    returns (uint256 p2pSupplyRate);

Parameters

NameTypeDescription
_paramsP2PRateComputeParamsThe computation parameters.

Returns

NameTypeDescription
p2pSupplyRateuint256The peer-to-peer supply rate per year (in ray).

computeP2PBorrowRatePerYear

Computes and returns the peer-to-peer borrow rate per year of a market given its parameters.

function computeP2PBorrowRatePerYear(P2PRateComputeParams memory _params)
    internal
    pure
    returns (uint256 p2pBorrowRate);

Parameters

NameTypeDescription
_paramsP2PRateComputeParamsThe computation parameters.

Returns

NameTypeDescription
p2pBorrowRateuint256The peer-to-peer borrow rate per year (in ray).

Structs

GrowthFactors

STRUCTS ///

struct GrowthFactors {
    uint256 poolSupplyGrowthFactor;
    uint256 poolBorrowGrowthFactor;
    uint256 p2pSupplyGrowthFactor;
    uint256 p2pBorrowGrowthFactor;
}

P2PIndexComputeParams

struct P2PIndexComputeParams {
    uint256 poolGrowthFactor;
    uint256 p2pGrowthFactor;
    uint256 lastPoolIndex;
    uint256 lastP2PIndex;
    uint256 p2pDelta;
    uint256 p2pAmount;
}

P2PRateComputeParams

struct P2PRateComputeParams {
    uint256 poolSupplyRatePerYear;
    uint256 poolBorrowRatePerYear;
    uint256 poolIndex;
    uint256 p2pIndex;
    uint256 p2pDelta;
    uint256 p2pAmount;
    uint256 p2pIndexCursor;
    uint256 reserveFactor;
}

Types

Git Source

Author: Morpho Labs.

Common types and structs used in Morpho contracts.

Structs

SupplyBalance

STRUCTS ///

struct SupplyBalance {
    uint256 inP2P;
    uint256 onPool;
}

BorrowBalance

struct BorrowBalance {
    uint256 inP2P;
    uint256 onPool;
}

Indexes

struct Indexes {
    uint256 p2pSupplyIndex;
    uint256 p2pBorrowIndex;
    uint256 poolSupplyIndex;
    uint256 poolBorrowIndex;
}

MaxGasForMatching

struct MaxGasForMatching {
    uint64 supply;
    uint64 borrow;
    uint64 withdraw;
    uint64 repay;
}

Delta

struct Delta {
    uint256 p2pSupplyDelta;
    uint256 p2pBorrowDelta;
    uint256 p2pSupplyAmount;
    uint256 p2pBorrowAmount;
}

AssetLiquidityData

struct AssetLiquidityData {
    uint256 decimals;
    uint256 tokenUnit;
    uint256 liquidationThreshold;
    uint256 ltv;
    uint256 underlyingPrice;
    uint256 collateralEth;
    uint256 debtEth;
}

LiquidityData

struct LiquidityData {
    uint256 collateralEth;
    uint256 borrowableEth;
    uint256 maxDebtEth;
    uint256 debtEth;
}

PoolIndexes

struct PoolIndexes {
    uint32 lastUpdateTimestamp;
    uint112 poolSupplyIndex;
    uint112 poolBorrowIndex;
}

Market

struct Market {
    address underlyingToken;
    uint16 reserveFactor;
    uint16 p2pIndexCursor;
    bool isCreated;
    bool isPaused;
    bool isPartiallyPaused;
    bool isP2PDisabled;
}

MarketPauseStatus

struct MarketPauseStatus {
    bool isSupplyPaused;
    bool isBorrowPaused;
    bool isWithdrawPaused;
    bool isRepayPaused;
    bool isLiquidateCollateralPaused;
    bool isLiquidateBorrowPaused;
    bool isDeprecated;
}

Enums

PositionType

ENUMS ///

enum PositionType {
    SUPPLIERS_IN_P2P,
    SUPPLIERS_ON_POOL,
    BORROWERS_IN_P2P,
    BORROWERS_ON_POOL
}

EntryPositionsManager

Git Source

Inherits: IEntryPositionsManager, PositionsManagerUtils

Author: Morpho Labs.

Morpho's entry points: supply and borrow.

Functions

supplyLogic

LOGIC ///

Implements supply logic.

function supplyLogic(address _poolToken, address _from, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching)
    external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token the user wants to interact with.
_fromaddressThe address of the account sending funds.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

borrowLogic

Peer-to-peer supply /// Pool supply ///

Implements borrow logic.

function borrowLogic(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

_borrowAllowed

Peer-to-peer borrow /// Pool borrow ///

Checks whether the user can borrow or not.

function _borrowAllowed(address _user, address _poolToken, uint256 _borrowedAmount) internal returns (bool);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_poolTokenaddressThe market to hypothetically borrow in.
_borrowedAmountuint256The amount of tokens to hypothetically borrow (in underlying).

Returns

NameTypeDescription
<none>boolWhether the borrow is allowed or not.

Events

Supplied

EVENTS ///

Emitted when a supply happens.

event Supplied(
    address indexed _from,
    address indexed _onBehalf,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Borrowed

Emitted when a borrow happens.

event Borrowed(
    address indexed _borrower,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Errors

BorrowingNotEnabled

ERRORS ///

Thrown when borrowing is impossible, because it is not enabled on pool for this specific market.

error BorrowingNotEnabled();

UnauthorisedBorrow

Thrown when the user does not have enough collateral for the borrow.

error UnauthorisedBorrow();

SupplyIsPaused

Thrown when someone tries to supply but the supply is paused.

error SupplyIsPaused();

BorrowIsPaused

Thrown when someone tries to borrow but the borrow is paused.

error BorrowIsPaused();

Structs

SupplyVars

STRUCTS ///

struct SupplyVars {
    uint256 remainingToSupply;
    uint256 poolBorrowIndex;
    uint256 toRepay;
}

ExitPositionsManager

Git Source

Inherits: IExitPositionsManager, PositionsManagerUtils

Author: Morpho Labs.

Morpho's exit points: withdraw, repay and liquidate.

Functions

withdrawLogic

LOGIC ///

Implements withdraw logic with security checks.

function withdrawLogic(
    address _poolToken,
    uint256 _amount,
    address _supplier,
    address _receiver,
    uint256 _maxGasForMatching
) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_supplieraddressThe address of the supplier.
_receiveraddressThe address of the user who will receive the tokens.
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

repayLogic

Implements repay logic with security checks.

function repayLogic(
    address _poolToken,
    address _repayer,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_repayeraddressThe address of the account repaying the debt.
_onBehalfaddressThe address of the account whose debt is repaid.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

liquidateLogic

Liquidates a position.

function liquidateLogic(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external;

Parameters

NameTypeDescription
_poolTokenBorrowedaddressThe address of the pool token the liquidator wants to repay.
_poolTokenCollateraladdressThe address of the collateral pool token the liquidator wants to seize.
_borroweraddressThe address of the borrower to liquidate.
_amountuint256The amount of token (in underlying) to repay.

increaseP2PDeltasLogic

Implements increaseP2PDeltas logic.

The current Morpho supply on the pool might not be enough to borrow _amount before resupplying it. In this case, consider calling this function multiple times.

function increaseP2PDeltasLogic(address _poolToken, uint256 _amount) external isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to increase deltas.
_amountuint256The maximum amount to add to the deltas (in underlying).

_unsafeWithdrawLogic

INTERNAL ///

Implements withdraw logic without security checks.

function _unsafeWithdrawLogic(
    address _poolToken,
    uint256 _amount,
    address _supplier,
    address _receiver,
    uint256 _maxGasForMatching
) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_supplieraddressThe address of the supplier.
_receiveraddressThe address of the user who will receive the tokens.
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

_unsafeRepayLogic

Pool withdraw /// Transfer withdraw /// Breaking withdraw ///

Implements repay logic without security checks.

function _unsafeRepayLogic(
    address _poolToken,
    address _repayer,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_repayeraddressThe address of the account repaying the debt.
_onBehalfaddressThe address of the account whose debt is repaid.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

_getUserHealthFactor

Pool repay /// Transfer repay /// Breaking repay ///

Returns the health factor of the user.

function _getUserHealthFactor(address _user, address _poolToken, uint256 _withdrawnAmount) internal returns (uint256);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_poolTokenaddressThe market to hypothetically withdraw from.
_withdrawnAmountuint256The number of tokens to hypothetically withdraw (in underlying).

Returns

NameTypeDescription
<none>uint256The health factor of the user.

_withdrawAllowed

Checks whether the user can withdraw or not.

function _withdrawAllowed(address _user, address _poolToken, uint256 _withdrawnAmount) internal returns (bool);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_poolTokenaddressThe market to hypothetically withdraw/borrow in.
_withdrawnAmountuint256The number of tokens to hypothetically withdraw (in underlying).

Returns

NameTypeDescription
<none>boolWhether the withdraw is allowed or not.

_liquidationAllowed

Returns whether a given user is liquidatable and the applicable close factor, given the deprecated status of the borrowed market.

function _liquidationAllowed(address _user, bool _isDeprecated)
    internal
    returns (bool liquidationAllowed, uint256 closeFactor);

Parameters

NameTypeDescription
_useraddressThe user to check.
_isDeprecatedboolWhether the borrowed market is deprecated or not.

Returns

NameTypeDescription
liquidationAllowedboolWhether the liquidation is allowed or not.
closeFactoruint256The close factor to apply.

Events

Withdrawn

EVENTS ///

Emitted when a withdrawal happens.

event Withdrawn(
    address indexed _supplier,
    address indexed _receiver,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Repaid

Emitted when a repayment happens.

event Repaid(
    address indexed _repayer,
    address indexed _onBehalf,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Liquidated

Emitted when a liquidation happens.

event Liquidated(
    address _liquidator,
    address indexed _liquidated,
    address indexed _poolTokenBorrowed,
    uint256 _amountRepaid,
    address indexed _poolTokenCollateral,
    uint256 _amountSeized
);

P2PDeltasIncreased

Emitted when the peer-to-peer deltas are increased by the governance.

event P2PDeltasIncreased(address indexed _poolToken, uint256 _amount);

Errors

UserNotMemberOfMarket

ERRORS ///

Thrown when user is not a member of the market.

error UserNotMemberOfMarket();

UnauthorisedWithdraw

Thrown when the user does not have enough remaining collateral to withdraw.

error UnauthorisedWithdraw();

UnauthorisedLiquidate

Thrown when the positions of the user is not liquidatable.

error UnauthorisedLiquidate();

WithdrawIsPaused

Thrown when someone tries to withdraw but the withdraw is paused.

error WithdrawIsPaused();

RepayIsPaused

Thrown when someone tries to repay but the repay is paused.

error RepayIsPaused();

LiquidateCollateralIsPaused

Thrown when someone tries to liquidate but the liquidation with this asset as collateral is paused.

error LiquidateCollateralIsPaused();

LiquidateBorrowIsPaused

Thrown when someone tries to liquidate but the liquidation with this asset as debt is paused.

error LiquidateBorrowIsPaused();

Structs

WithdrawVars

STRUCTS ///

struct WithdrawVars {
    uint256 remainingGasForMatching;
    uint256 remainingToWithdraw;
    uint256 poolSupplyIndex;
    uint256 p2pSupplyIndex;
    uint256 onPoolSupply;
    uint256 toWithdraw;
}

RepayVars

struct RepayVars {
    uint256 remainingGasForMatching;
    uint256 remainingToRepay;
    uint256 poolSupplyIndex;
    uint256 poolBorrowIndex;
    uint256 p2pSupplyIndex;
    uint256 p2pBorrowIndex;
    uint256 borrowedOnPool;
    uint256 feeToRepay;
    uint256 toRepay;
}

LiquidateVars

struct LiquidateVars {
    uint256 liquidationBonus;
    uint256 collateralReserveDecimals;
    uint256 collateralTokenUnit;
    uint256 collateralBalance;
    uint256 collateralPrice;
    uint256 amountToSeize;
    uint256 borrowedReserveDecimals;
    uint256 borrowedTokenUnit;
    uint256 borrowedTokenPrice;
    uint256 amountToLiquidate;
    uint256 closeFactor;
    bool liquidationAllowed;
}

InterestRatesManager

Git Source

Inherits: IInterestRatesManager, MorphoStorage

Author: Morpho Labs.

Smart contract handling the computation of indexes used for peer-to-peer interactions.

This contract inherits from MorphoStorage so that Morpho can delegate calls to this contract.

Functions

updateIndexes

EXTERNAL ///

Updates the peer-to-peer indexes and pool indexes (only stored locally).

function updateIndexes(address _poolToken) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.

_getPoolIndexes

INTERNAL ///

Returns the current pool indexes.

function _getPoolIndexes(address _underlyingToken)
    internal
    view
    returns (uint256 poolSupplyIndex, uint256 poolBorrowIndex);

Parameters

NameTypeDescription
_underlyingTokenaddressThe address of the underlying token.

Returns

NameTypeDescription
poolSupplyIndexuint256The pool supply index.
poolBorrowIndexuint256The pool borrow index.

_computeP2PIndexes

Computes and returns new peer-to-peer indexes.

function _computeP2PIndexes(Params memory _params)
    internal
    pure
    returns (uint256 newP2PSupplyIndex, uint256 newP2PBorrowIndex);

Parameters

NameTypeDescription
_paramsParamsComputation parameters.

Returns

NameTypeDescription
newP2PSupplyIndexuint256The updated p2pSupplyIndex.
newP2PBorrowIndexuint256The updated p2pBorrowIndex.

Events

P2PIndexesUpdated

EVENTS ///

Emitted when the peer-to-peer indexes of a market are updated.

event P2PIndexesUpdated(
    address indexed _poolToken,
    uint256 _p2pSupplyIndex,
    uint256 _p2pBorrowIndex,
    uint256 _poolSupplyIndex,
    uint256 _poolBorrowIndex
);

Structs

Params

STRUCTS ///

struct Params {
    uint256 lastP2PSupplyIndex;
    uint256 lastP2PBorrowIndex;
    uint256 poolSupplyIndex;
    uint256 poolBorrowIndex;
    Types.PoolIndexes lastPoolIndexes;
    uint256 reserveFactor;
    uint256 p2pIndexCursor;
    Types.Delta delta;
}

MatchingEngine

Git Source

Inherits: MorphoUtils

Author: Morpho Labs.

Smart contract managing the matching engine.

Functions

_matchSuppliers

INTERNAL ///

Matches suppliers' liquidity waiting on Aave up to the given _amount and moves it to peer-to-peer.

Note: This function expects Aave's exchange rate and peer-to-peer indexes to have been updated.

function _matchSuppliers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256 matched, uint256 gasConsumedInMatching);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to match suppliers.
_amountuint256The token amount to search for (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
matcheduint256The amount of liquidity matched (in underlying).
gasConsumedInMatchinguint256The amount of gas consumed within the matching loop.

_unmatchSuppliers

Unmatches suppliers' liquidity in peer-to-peer up to the given _amount and moves it to Aave.

Note: This function expects Aave's exchange rate and peer-to-peer indexes to have been updated.

function _unmatchSuppliers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256 unmatched);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to unmatch suppliers.
_amountuint256The amount to search for (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
unmatcheduint256The amount unmatched (in underlying).

_matchBorrowers

Matches borrowers' liquidity waiting on Aave up to the given _amount and moves it to peer-to-peer.

Note: This function expects stored indexes to have been updated.

function _matchBorrowers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256 matched, uint256 gasConsumedInMatching);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to match borrowers.
_amountuint256The amount to search for (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
matcheduint256The amount of liquidity matched (in underlying).
gasConsumedInMatchinguint256The amount of gas consumed within the matching loop.

_unmatchBorrowers

Unmatches borrowers' liquidity in peer-to-peer for the given _amount and moves it to Aave.

Note: This function expects and peer-to-peer indexes to have been updated.

function _unmatchBorrowers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256 unmatched);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to unmatch borrowers.
_amountuint256The amount to unmatch (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
unmatcheduint256The amount unmatched (in underlying).

_updateSupplierInDS

Updates the given _user's position in the supplier data structures.

function _updateSupplierInDS(address _poolToken, address _user) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to update the suppliers data structure.
_useraddressThe address of the user.

_updateBorrowerInDS

Updates the given _user's position in the borrower data structures.

function _updateBorrowerInDS(address _poolToken, address _user) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to update the borrowers data structure.
_useraddressThe address of the user.

Events

SupplierPositionUpdated

Emitted when the position of a supplier is updated.

event SupplierPositionUpdated(
    address indexed _user, address indexed _poolToken, uint256 _balanceOnPool, uint256 _balanceInP2P
);

BorrowerPositionUpdated

Emitted when the position of a borrower is updated.

event BorrowerPositionUpdated(
    address indexed _user, address indexed _poolToken, uint256 _balanceOnPool, uint256 _balanceInP2P
);

Structs

UnmatchVars

STRUCTS ///

struct UnmatchVars {
    uint256 p2pIndex;
    uint256 toUnmatch;
    uint256 poolIndex;
}

MatchVars

struct MatchVars {
    uint256 p2pIndex;
    uint256 toMatch;
    uint256 poolIndex;
}

Morpho

Git Source

Inherits: MorphoGovernance

Author: Morpho Labs.

Main Morpho contract handling user interactions and pool interactions.

Functions

supply

EXTERNAL ///

Supplies underlying tokens to a specific market.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function supply(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying) to supply.

supply

Supplies underlying tokens to a specific market, on behalf of a given user.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function supply(address _poolToken, address _onBehalf, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying) to supply.

supply

Supplies underlying tokens to a specific market, on behalf of a given user, specifying a gas threshold at which to cut the matching engine.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching)
    external
    nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying) to supply.
_maxGasForMatchinguint256The gas threshold at which to stop the matching engine.

borrow

Borrows underlying tokens from a specific market.

function borrow(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).

borrow

Borrows underlying tokens from a specific market, specifying a gas threshold at which to stop the matching engine.

function borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The gas threshold at which to stop the matching engine.

withdraw

Withdraws underlying tokens from a specific market.

function withdraw(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of tokens (in underlying) to withdraw from supply.

withdraw

Withdraws underlying tokens from a specific market.

function withdraw(address _poolToken, uint256 _amount, address _receiver) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of tokens (in underlying) to withdraw from supply.
_receiveraddressThe address to send withdrawn tokens to.

repay

Repays the debt of the sender, up to the amount provided.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function repay(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying) to repay from borrow.

repay

Repays debt of a given user, up to the amount provided.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function repay(address _poolToken, address _onBehalf, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying) to repay from borrow.

liquidate

Liquidates a position.

function liquidate(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external
    nonReentrant;

Parameters

NameTypeDescription
_poolTokenBorrowedaddressThe address of the pool token the liquidator wants to repay.
_poolTokenCollateraladdressThe address of the collateral pool token the liquidator wants to seize.
_borroweraddressThe address of the borrower to liquidate.
_amountuint256The amount of token (in underlying) to repay.

claimRewards

Deprecated.

function claimRewards(address[] calldata, bool) external returns (uint256);

_supply

INTERNAL ///

function _supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) internal;

_borrow

function _borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) internal;

_withdraw

function _withdraw(address _poolToken, uint256 _amount, address _receiver, uint256 _maxGasForMatching) internal;

_repay

function _repay(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) internal;

MorphoGovernance

Git Source

Inherits: MorphoUtils

Author: Morpho Labs.

Governance functions for Morpho.

Functions

initialize

UPGRADE ///

Initializes the Morpho contract.

function initialize(
    IEntryPositionsManager _entryPositionsManager,
    IExitPositionsManager _exitPositionsManager,
    IInterestRatesManager _interestRatesManager,
    ILendingPoolAddressesProvider _lendingPoolAddressesProvider,
    Types.MaxGasForMatching memory _defaultMaxGasForMatching,
    uint256 _maxSortedUsers
) external initializer;

Parameters

NameTypeDescription
_entryPositionsManagerIEntryPositionsManagerThe entryPositionsManager.
_exitPositionsManagerIExitPositionsManagerThe exitPositionsManager.
_interestRatesManagerIInterestRatesManagerThe interestRatesManager.
_lendingPoolAddressesProviderILendingPoolAddressesProviderThe addressesProvider.
_defaultMaxGasForMatchingTypes.MaxGasForMatchingThe defaultMaxGasForMatching.
_maxSortedUsersuint256The _maxSortedUsers.

setMaxSortedUsers

GOVERNANCE ///

Sets maxSortedUsers.

function setMaxSortedUsers(uint256 _newMaxSortedUsers) external onlyOwner;

Parameters

NameTypeDescription
_newMaxSortedUsersuint256The new maxSortedUsers value.

setDefaultMaxGasForMatching

Sets defaultMaxGasForMatching.

function setDefaultMaxGasForMatching(Types.MaxGasForMatching memory _defaultMaxGasForMatching) external onlyOwner;

Parameters

NameTypeDescription
_defaultMaxGasForMatchingTypes.MaxGasForMatchingThe new defaultMaxGasForMatching.

setEntryPositionsManager

Sets the entryPositionsManager.

function setEntryPositionsManager(IEntryPositionsManager _entryPositionsManager) external onlyOwner;

Parameters

NameTypeDescription
_entryPositionsManagerIEntryPositionsManagerThe new entryPositionsManager.

setExitPositionsManager

Sets the exitPositionsManager.

function setExitPositionsManager(IExitPositionsManager _exitPositionsManager) external onlyOwner;

Parameters

NameTypeDescription
_exitPositionsManagerIExitPositionsManagerThe new exitPositionsManager.

setInterestRatesManager

Sets the interestRatesManager.

function setInterestRatesManager(IInterestRatesManager _interestRatesManager) external onlyOwner;

Parameters

NameTypeDescription
_interestRatesManagerIInterestRatesManagerThe new interestRatesManager contract.

setTreasuryVault

Sets the treasuryVault.

function setTreasuryVault(address _treasuryVault) external onlyOwner;

Parameters

NameTypeDescription
_treasuryVaultaddressThe address of the new treasuryVault.

setReserveFactor

Sets the reserveFactor.

function setReserveFactor(address _poolToken, uint16 _newReserveFactor)
    external
    onlyOwner
    isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe market on which to set the _newReserveFactor.
_newReserveFactoruint16The proportion of the interest earned by users sent to the DAO, in basis point.

setP2PIndexCursor

Sets a new peer-to-peer cursor.

function setP2PIndexCursor(address _poolToken, uint16 _p2pIndexCursor) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_p2pIndexCursoruint16The new peer-to-peer cursor.

setIsSupplyPaused

Sets isSupplyPaused for a given market.

function setIsSupplyPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsBorrowPaused

Sets isBorrowPaused for a given market.

function setIsBorrowPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsWithdrawPaused

Sets isWithdrawPaused for a given market.

function setIsWithdrawPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsRepayPaused

Sets isRepayPaused for a given market.

function setIsRepayPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsLiquidateCollateralPaused

Sets isLiquidateCollateralPaused for a given market.

function setIsLiquidateCollateralPaused(address _poolToken, bool _isPaused)
    external
    onlyOwner
    isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsLiquidateBorrowPaused

Sets isLiquidateBorrowPaused for a given market.

function setIsLiquidateBorrowPaused(address _poolToken, bool _isPaused)
    external
    onlyOwner
    isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsPausedForAllMarkets

Sets the pause status for all markets.

function setIsPausedForAllMarkets(bool _isPaused) external onlyOwner;

Parameters

NameTypeDescription
_isPausedboolThe new pause status, true to pause the mechanism.

setIsP2PDisabled

Sets isP2PDisabled for a given market.

function setIsP2PDisabled(address _poolToken, bool _isP2PDisabled) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to enable/disable peer-to-peer matching.
_isP2PDisabledboolTrue to disable the peer-to-peer market.

setIsDeprecated

Sets a market as deprecated (allows liquidation of every position on this market).

function setIsDeprecated(address _poolToken, bool _isDeprecated) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isDeprecatedboolThe new deprecated status, true to deprecate the market.

increaseP2PDeltas

Increases peer-to-peer deltas, to put some liquidity back on the pool.

The current Morpho supply on the pool might not be enough to borrow _amount before resuppling it. In this case, consider calling multiple times this function.

function increaseP2PDeltas(address _poolToken, uint256 _amount) external onlyOwner;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to increase deltas.
_amountuint256The maximum amount to add to the deltas (in underlying).

claimToTreasury

Transfers the protocol reserve fee to the DAO.

function claimToTreasury(address[] calldata _poolTokens, uint256[] calldata _amounts) external onlyOwner;

Parameters

NameTypeDescription
_poolTokensaddress[]The addresses of the pool token addresses on which to claim the reserve fee.
_amountsuint256[]The list of amounts of underlying tokens to claim on each market.

createMarket

Creates a new market to borrow/supply in.

function createMarket(address _underlyingToken, uint16 _reserveFactor, uint16 _p2pIndexCursor) external onlyOwner;

Parameters

NameTypeDescription
_underlyingTokenaddressThe underlying token address.
_reserveFactoruint16The reserve factor to set on this market.
_p2pIndexCursoruint16The peer-to-peer index cursor to set on this market.

_setPauseStatus

INTERNAL ///

Sets all pause statuses for a given market.

function _setPauseStatus(address _poolToken, bool _isPaused) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

Events

DefaultMaxGasForMatchingSet

EVENTS ///

Emitted when a new defaultMaxGasForMatching is set.

event DefaultMaxGasForMatchingSet(Types.MaxGasForMatching _defaultMaxGasForMatching);

MaxSortedUsersSet

Emitted when a new value for maxSortedUsers is set.

event MaxSortedUsersSet(uint256 _newValue);

TreasuryVaultSet

Emitted when the address of the treasuryVault is set.

event TreasuryVaultSet(address indexed _newTreasuryVaultAddress);

EntryPositionsManagerSet

Emitted when the entryPositionsManager is set.

event EntryPositionsManagerSet(address indexed _entryPositionsManager);

ExitPositionsManagerSet

Emitted when the exitPositionsManager is set.

event ExitPositionsManagerSet(address indexed _exitPositionsManager);

InterestRatesSet

Emitted when the interestRatesManager is set.

event InterestRatesSet(address indexed _interestRatesManager);

ReserveFactorSet

Emitted when the reserveFactor is set.

event ReserveFactorSet(address indexed _poolToken, uint16 _newValue);

P2PIndexCursorSet

Emitted when the p2pIndexCursor is set.

event P2PIndexCursorSet(address indexed _poolToken, uint16 _newValue);

ReserveFeeClaimed

Emitted when a reserve fee is claimed.

event ReserveFeeClaimed(address indexed _poolToken, uint256 _amountClaimed);

P2PStatusSet

Emitted when the value of isP2PDisabled is set.

event P2PStatusSet(address indexed _poolToken, bool _isP2PDisabled);

IsSupplyPausedSet

Emitted when supplying is paused or unpaused.

event IsSupplyPausedSet(address indexed _poolToken, bool _isPaused);

IsBorrowPausedSet

Emitted when borrowing is paused or unpaused.

event IsBorrowPausedSet(address indexed _poolToken, bool _isPaused);

IsWithdrawPausedSet

Emitted when withdrawing is paused or unpaused.

event IsWithdrawPausedSet(address indexed _poolToken, bool _isPaused);

IsRepayPausedSet

Emitted when repaying is paused or unpaused.

event IsRepayPausedSet(address indexed _poolToken, bool _isPaused);

IsLiquidateCollateralPausedSet

Emitted when liquidating on this market as collateral is paused or unpaused.

event IsLiquidateCollateralPausedSet(address indexed _poolToken, bool _isPaused);

IsLiquidateBorrowPausedSet

Emitted when liquidating on this market as borrow is paused or unpaused.

event IsLiquidateBorrowPausedSet(address indexed _poolToken, bool _isPaused);

IsDeprecatedSet

Emitted when a market is set as deprecated or not.

event IsDeprecatedSet(address indexed _poolToken, bool _isDeprecated);

MarketCreated

Emitted when a new market is created.

event MarketCreated(address indexed _poolToken, uint16 _reserveFactor, uint16 _p2pIndexCursor);

Errors

MarketIsNotListedOnAave

ERRORS ///

Thrown when the market is not listed on Aave.

error MarketIsNotListedOnAave();

ExceedsMaxBasisPoints

Thrown when the input is above the max basis points value (100%).

error ExceedsMaxBasisPoints();

MarketAlreadyCreated

Thrown when the market is already created.

error MarketAlreadyCreated();

MaxSortedUsersCannotBeZero

Thrown when trying to set the max sorted users to 0.

error MaxSortedUsersCannotBeZero();

MaxNumberOfMarkets

Thrown when the number of markets will exceed the bitmask's capacity.

error MaxNumberOfMarkets();

ZeroAddress

Thrown when the address is the zero address.

error ZeroAddress();

BorrowNotPaused

Thrown when market borrow is not paused.

error BorrowNotPaused();

MarketIsDeprecated

Thrown when market is deprecated.

error MarketIsDeprecated();

MorphoStorage

Git Source

Inherits: OwnableUpgradeable, ReentrancyGuardUpgradeable

Author: Morpho Labs.

All storage variables used in Morpho contracts.

State Variables

NO_REFERRAL_CODE

GLOBAL STORAGE ///

uint8 public constant NO_REFERRAL_CODE = 0;

VARIABLE_INTEREST_MODE

uint8 public constant VARIABLE_INTEREST_MODE = 2;

MAX_BASIS_POINTS

uint16 public constant MAX_BASIS_POINTS = 100_00;

DEFAULT_LIQUIDATION_CLOSE_FACTOR

uint256 public constant DEFAULT_LIQUIDATION_CLOSE_FACTOR = 50_00;

HEALTH_FACTOR_LIQUIDATION_THRESHOLD

uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;

MAX_NB_OF_MARKETS

uint256 public constant MAX_NB_OF_MARKETS = 128;

BORROWING_MASK

bytes32 public constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555;

ONE

bytes32 public constant ONE = 0x0000000000000000000000000000000000000000000000000000000000000001;

ST_ETH

address public constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;

ST_ETH_BASE_REBASE_INDEX

uint256 public constant ST_ETH_BASE_REBASE_INDEX = 1_086492192583716523804482274;

isClaimRewardsPaused

bool public isClaimRewardsPaused;

maxSortedUsers

uint256 public maxSortedUsers;

defaultMaxGasForMatching

Types.MaxGasForMatching public defaultMaxGasForMatching;

suppliersInP2P

POSITIONS STORAGE ///

mapping(address => HeapOrdering.HeapArray) internal suppliersInP2P;

suppliersOnPool

mapping(address => HeapOrdering.HeapArray) internal suppliersOnPool;

borrowersInP2P

mapping(address => HeapOrdering.HeapArray) internal borrowersInP2P;

borrowersOnPool

mapping(address => HeapOrdering.HeapArray) internal borrowersOnPool;

supplyBalanceInOf

mapping(address => mapping(address => Types.SupplyBalance)) public supplyBalanceInOf;

borrowBalanceInOf

mapping(address => mapping(address => Types.BorrowBalance)) public borrowBalanceInOf;

userMarkets

mapping(address => bytes32) public userMarkets;

marketsCreated

MARKETS STORAGE ///

address[] internal marketsCreated;

p2pSupplyIndex

mapping(address => uint256) public p2pSupplyIndex;

p2pBorrowIndex

mapping(address => uint256) public p2pBorrowIndex;

poolIndexes

mapping(address => Types.PoolIndexes) public poolIndexes;

market

mapping(address => Types.Market) public market;

deltas

mapping(address => Types.Delta) public deltas;

borrowMask

mapping(address => bytes32) public borrowMask;

addressesProvider

CONTRACTS AND ADDRESSES ///

ILendingPoolAddressesProvider public addressesProvider;

aaveIncentivesController

address public aaveIncentivesController;

pool

ILendingPool public pool;

entryPositionsManager

IEntryPositionsManager public entryPositionsManager;

exitPositionsManager

IExitPositionsManager public exitPositionsManager;

interestRatesManager

IInterestRatesManager public interestRatesManager;

incentivesVault

address public incentivesVault;

rewardsManager

address public rewardsManager;

treasuryVault

address public treasuryVault;

marketPauseStatus

APPENDIX STORAGE ///

mapping(address => Types.MarketPauseStatus) public marketPauseStatus;

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

The contract is automatically marked as initialized when deployed so that nobody can highjack the implementation contract.

constructor() initializer;

MorphoUtils

Git Source

Inherits: MorphoStorage

Author: Morpho Labs.

Modifiers, getters and other util functions for Morpho.

Functions

isMarketCreated

MODIFIERS ///

Prevents to update a market not created yet.

modifier isMarketCreated(address _poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

getMarketsCreated

EXTERNAL ///

Returns all created markets.

function getMarketsCreated() external view returns (address[] memory);

Returns

NameTypeDescription
<none>address[]marketsCreated_ The list of market addresses.

getHead

Gets the head of the data structure on a specific market (for UI).

function getHead(address _poolToken, Types.PositionType _positionType) external view returns (address head);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to get the head.
_positionTypeTypes.PositionTypeThe type of user from which to get the head.

Returns

NameTypeDescription
headaddressThe head in the data structure.

getNext

Gets the next user after _user in the data structure on a specific market (for UI).

Beware that this function does not give the account with the highest liquidity.

function getNext(address _poolToken, Types.PositionType _positionType, address _user)
    external
    view
    returns (address next);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to get the user.
_positionTypeTypes.PositionTypeThe type of user from which to get the next user.
_useraddressThe address of the user from which to get the next user.

Returns

NameTypeDescription
nextaddressThe next user in the data structure.

updateIndexes

Updates the peer-to-peer indexes and pool indexes (only stored locally).

function updateIndexes(address _poolToken) external isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.

_isSupplyingOrBorrowing

INTERNAL ///

Returns if a user has been borrowing or supplying on a given market.

function _isSupplyingOrBorrowing(bytes32 _userMarkets, bytes32 _borrowMask) internal pure returns (bool);

Parameters

NameTypeDescription
_userMarketsbytes32The bitmask encoding the markets entered by the user.
_borrowMaskbytes32The borrow mask of the market to check.

Returns

NameTypeDescription
<none>boolTrue if the user has been supplying or borrowing on this market, false otherwise.

_isBorrowing

Returns if a user is borrowing on a given market.

function _isBorrowing(bytes32 _userMarkets, bytes32 _borrowMask) internal pure returns (bool);

Parameters

NameTypeDescription
_userMarketsbytes32The bitmask encoding the markets entered by the user.
_borrowMaskbytes32The borrow mask of the market to check.

Returns

NameTypeDescription
<none>boolTrue if the user has been borrowing on this market, false otherwise.

_isSupplying

Returns if a user is supplying on a given market.

function _isSupplying(bytes32 _userMarkets, bytes32 _borrowMask) internal pure returns (bool);

Parameters

NameTypeDescription
_userMarketsbytes32The bitmask encoding the markets entered by the user.
_borrowMaskbytes32The borrow mask of the market to check.

Returns

NameTypeDescription
<none>boolTrue if the user has been supplying on this market, false otherwise.

_isBorrowingAny

Returns if a user has been borrowing from any market.

function _isBorrowingAny(bytes32 _userMarkets) internal pure returns (bool);

Parameters

NameTypeDescription
_userMarketsbytes32The bitmask encoding the markets entered by the user.

Returns

NameTypeDescription
<none>boolTrue if the user has been borrowing on any market, false otherwise.

_isBorrowingAndSupplying

Returns if a user is borrowing on a given market and supplying on another given market.

function _isBorrowingAndSupplying(bytes32 _userMarkets, bytes32 _borrowedBorrowMask, bytes32 _suppliedBorrowMask)
    internal
    pure
    returns (bool);

Parameters

NameTypeDescription
_userMarketsbytes32The bitmask encoding the markets entered by the user.
_borrowedBorrowMaskbytes32The borrow mask of the market to check whether the user is borrowing.
_suppliedBorrowMaskbytes32The borrow mask of the market to check whether the user is supplying.

Returns

NameTypeDescription
<none>boolTrue if the user is borrowing on the given market and supplying on the other given market, false otherwise.

_setBorrowing

Sets if the user is borrowing on a market.

function _setBorrowing(address _user, bytes32 _borrowMask, bool _borrowing) internal;

Parameters

NameTypeDescription
_useraddressThe user to set for.
_borrowMaskbytes32The borrow mask of the market to mark as borrowed.
_borrowingboolTrue if the user is borrowing, false otherwise.

_setSupplying

Sets if the user is supplying on a market.

function _setSupplying(address _user, bytes32 _borrowMask, bool _supplying) internal;

Parameters

NameTypeDescription
_useraddressThe user to set for.
_borrowMaskbytes32The borrow mask of the market to mark as supplied.
_supplyingboolTrue if the user is supplying, false otherwise.

_updateIndexes

Updates the peer-to-peer indexes and pool indexes (only stored locally).

function _updateIndexes(address _poolToken) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.

_getUserSupplyBalanceInOf

Returns the supply balance of _user in the _poolToken market.

Note: Computes the result with the stored indexes, which are not always the most up to date ones.

function _getUserSupplyBalanceInOf(address _poolToken, address _user) internal view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the supply amount.
_useraddressThe address of the user.

Returns

NameTypeDescription
<none>uint256The supply balance of the user (in underlying).

_getUserBorrowBalanceInOf

Returns the borrow balance of _user in the _poolToken market.

Note: Computes the result with the stored indexes, which are not always the most up to date ones.

function _getUserBorrowBalanceInOf(address _poolToken, address _user) internal view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the borrow amount.
_useraddressThe address of the user.

Returns

NameTypeDescription
<none>uint256The borrow balance of the user (in underlying).

_collateralValue

Calculates the value of the collateral.

function _collateralValue(address _poolToken, address _user, uint256 _underlyingPrice, uint256 _tokenUnit)
    internal
    view
    returns (uint256 collateral);

Parameters

NameTypeDescription
_poolTokenaddressThe pool token to calculate the value for.
_useraddressThe user address.
_underlyingPriceuint256The underlying price.
_tokenUnituint256The token unit.

_debtValue

Calculates the value of the debt.

function _debtValue(address _poolToken, address _user, uint256 _underlyingPrice, uint256 _tokenUnit)
    internal
    view
    returns (uint256 debt);

Parameters

NameTypeDescription
_poolTokenaddressThe pool token to calculate the value for.
_useraddressThe user address.
_underlyingPriceuint256The underlying price.
_tokenUnituint256The token unit.

_liquidityData

Calculates the total value of the collateral, debt, and LTV/LT value depending on the calculation type.

Expects the given user's entered markets to include the given market.

Expects the given market's pool & peer-to-peer indexes to have been updated.

Expects _amountWithdrawn to be less than or equal to the given user's supply on the given market.

function _liquidityData(address _user, address _poolToken, uint256 _amountWithdrawn, uint256 _amountBorrowed)
    internal
    returns (Types.LiquidityData memory values);

Parameters

NameTypeDescription
_useraddressThe user address.
_poolTokenaddressThe pool token that is being borrowed or withdrawn.
_amountWithdrawnuint256The amount that is being withdrawn.
_amountBorroweduint256The amount that is being borrowed.

Returns

NameTypeDescription
valuesTypes.LiquidityDataThe struct containing health factor, collateral, debt, ltv, liquidation threshold values.

Errors

MarketNotCreated

ERRORS ///

Thrown when the market is not created yet.

error MarketNotCreated();

Structs

LiquidityVars

STRUCTS ///

struct LiquidityVars {
    address poolToken;
    uint256 poolTokensLength;
    bytes32 userMarkets;
    bytes32 borrowMask;
    address underlyingToken;
    uint256 underlyingPrice;
}

PositionsManagerUtils

Git Source

Inherits: MatchingEngine

Author: Morpho Labs.

Utils shared by the EntryPositionsManager and ExitPositionsManager.

Functions

_supplyToPool

POOL INTERACTION ///

Supplies underlying tokens to Aave.

function _supplyToPool(ERC20 _underlyingToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_underlyingTokenERC20The underlying token of the market to supply to.
_amountuint256The amount of token (in underlying).

_withdrawFromPool

Withdraws underlying tokens from Aave.

function _withdrawFromPool(ERC20 _underlyingToken, address _poolToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_underlyingTokenERC20The underlying token of the market to withdraw from.
_poolTokenaddressThe address of the market.
_amountuint256The amount of token (in underlying).

_borrowFromPool

Borrows underlying tokens from Aave.

function _borrowFromPool(ERC20 _underlyingToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_underlyingTokenERC20The underlying token of the market to borrow from.
_amountuint256The amount of token (in underlying).

_repayToPool

Repays underlying tokens to Aave.

function _repayToPool(ERC20 _underlyingToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_underlyingTokenERC20The underlying token of the market to repay to.
_amountuint256The amount of token (in underlying).

Events

P2PBorrowDeltaUpdated

COMMON EVENTS ///

Emitted when the peer-to-peer borrow delta is updated.

event P2PBorrowDeltaUpdated(address indexed _poolToken, uint256 _p2pBorrowDelta);

P2PSupplyDeltaUpdated

Emitted when the peer-to-peer supply delta is updated.

event P2PSupplyDeltaUpdated(address indexed _poolToken, uint256 _p2pSupplyDelta);

P2PAmountsUpdated

Emitted when the supply and peer-to-peer borrow amounts are updated.

event P2PAmountsUpdated(address indexed _poolToken, uint256 _p2pSupplyAmount, uint256 _p2pBorrowAmount);

Errors

AddressIsZero

COMMON ERRORS ///

Thrown when the address is zero.

error AddressIsZero();

AmountIsZero

Thrown when the amount is equal to 0.

error AmountIsZero();

Contents

Contents

RewardsDistributor

Git Source

Inherits: Ownable

Author: Morpho Labs.

This contract allows Morpho users to claim their rewards. This contract is largely inspired by Euler Distributor's contract: https://github.com/euler-xyz/euler-contracts/blob/master/contracts/mining/EulDistributor.sol.

State Variables

MORPHO

STORAGE ///

ERC20 public immutable MORPHO;

currRoot

bytes32 public currRoot;

prevRoot

bytes32 public prevRoot;

claimed

mapping(address => uint256) public claimed;

Functions

constructor

CONSTRUCTOR ///

Constructs Morpho's RewardsDistributor contract.

constructor(address _morpho);

Parameters

NameTypeDescription
_morphoaddressThe address of the MORPHO token to distribute.

updateRoot

EXTERNAL ///

Updates the current merkle tree's root.

function updateRoot(bytes32 _newRoot) external onlyOwner;

Parameters

NameTypeDescription
_newRootbytes32The new merkle tree's root.

withdrawMorphoTokens

Withdraws MORPHO tokens to a recipient.

function withdrawMorphoTokens(address _to, uint256 _amount) external onlyOwner;

Parameters

NameTypeDescription
_toaddressThe address of the recipient.
_amountuint256The amount of MORPHO tokens to transfer.

claim

Claims rewards.

function claim(address _account, uint256 _claimable, bytes32[] calldata _proof) external;

Parameters

NameTypeDescription
_accountaddressThe address of the claimer.
_claimableuint256The overall claimable amount of token rewards.
_proofbytes32[]The merkle proof that validates this claim.

Events

RootUpdated

EVENTS ///

Emitted when the root is updated.

event RootUpdated(bytes32 newRoot);

MorphoWithdrawn

Emitted when MORPHO tokens are withdrawn.

event MorphoWithdrawn(address to, uint256 amount);

RewardsClaimed

Emitted when an account claims rewards.

event RewardsClaimed(address account, uint256 amount);

Errors

ProofInvalidOrExpired

ERRORS ///

Thrown when the proof is invalid or expired.

error ProofInvalidOrExpired();

AlreadyClaimed

Thrown when the claimer has already claimed the rewards.

error AlreadyClaimed();

Contents

FakeToken

Git Source

Inherits: ERC20

Functions

constructor

constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol);

mint

function mint(address _receiver, uint256 _amount) external;

Contents

Contents

Contents

ICEth

Git Source

Functions

accrueInterest

function accrueInterest() external returns (uint256);

borrowRate

function borrowRate() external returns (uint256);

borrowIndex

function borrowIndex() external returns (uint256);

borrowBalanceStored

function borrowBalanceStored(address) external returns (uint256);

mint

function mint() external payable;

exchangeRateCurrent

function exchangeRateCurrent() external returns (uint256);

exchangeRateStored

function exchangeRateStored() external view returns (uint256);

supplyRatePerBlock

function supplyRatePerBlock() external returns (uint256);

redeem

function redeem(uint256) external returns (uint256);

redeemUnderlying

function redeemUnderlying(uint256) external returns (uint256);

approve

function approve(address spender, uint256 amount) external returns (bool);

transferFrom

function transferFrom(address, address, uint256) external returns (bool);

transfer

function transfer(address dst, uint256 amount) external returns (bool);

balanceOf

function balanceOf(address) external returns (uint256);

balanceOfUnderlying

function balanceOfUnderlying(address account) external returns (uint256);

borrow

function borrow(uint256) external returns (uint256);

repayBorrow

function repayBorrow() external payable;

borrowBalanceCurrent

function borrowBalanceCurrent(address) external returns (uint256);

borrowRatePerBlock

function borrowRatePerBlock() external view returns (uint256);

IComptroller

Git Source

Functions

liquidationIncentiveMantissa

function liquidationIncentiveMantissa() external view returns (uint256);

closeFactorMantissa

function closeFactorMantissa() external view returns (uint256);

admin

function admin() external view returns (address);

allMarkets

function allMarkets(uint256) external view returns (ICToken);

oracle

function oracle() external view returns (address);

borrowCaps

function borrowCaps(address) external view returns (uint256);

markets

function markets(address) external view returns (bool isListed, uint256 collateralFactorMantissa, bool isComped);

enterMarkets

function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);

exitMarket

function exitMarket(address cToken) external returns (uint256);

mintAllowed

function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);

mintVerify

function mintVerify(address cToken, address minter, uint256 mintAmount, uint256 mintTokens) external;

redeemAllowed

function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external returns (uint256);

redeemVerify

function redeemVerify(address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external;

borrowAllowed

function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external returns (uint256);

borrowVerify

function borrowVerify(address cToken, address borrower, uint256 borrowAmount) external;

repayBorrowAllowed

function repayBorrowAllowed(address cToken, address payer, address borrower, uint256 repayAmount)
    external
    returns (uint256);

repayBorrowVerify

function repayBorrowVerify(address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex)
    external;

liquidateBorrowAllowed

function liquidateBorrowAllowed(
    address cTokenBorrowed,
    address cTokenCollateral,
    address liquidator,
    address borrower,
    uint256 repayAmount
) external returns (uint256);

liquidateBorrowVerify

function liquidateBorrowVerify(
    address cTokenBorrowed,
    address cTokenCollateral,
    address liquidator,
    address borrower,
    uint256 repayAmount,
    uint256 seizeTokens
) external;

seizeAllowed

function seizeAllowed(
    address cTokenCollateral,
    address cTokenBorrowed,
    address liquidator,
    address borrower,
    uint256 seizeTokens
) external returns (uint256);

seizeVerify

function seizeVerify(
    address cTokenCollateral,
    address cTokenBorrowed,
    address liquidator,
    address borrower,
    uint256 seizeTokens
) external;

transferAllowed

function transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256);

transferVerify

function transferVerify(address cToken, address src, address dst, uint256 transferTokens) external;

liquidateCalculateSeizeTokens

Liquidity/Liquidation Calculations **

function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount)
    external
    view
    returns (uint256, uint256);

getAccountLiquidity

function getAccountLiquidity(address) external view returns (uint256, uint256, uint256);

getHypotheticalAccountLiquidity

function getHypotheticalAccountLiquidity(address, address, uint256, uint256)
    external
    returns (uint256, uint256, uint256);

checkMembership

function checkMembership(address, address) external view returns (bool);

mintGuardianPaused

function mintGuardianPaused(address) external view returns (bool);

borrowGuardianPaused

function borrowGuardianPaused(address) external view returns (bool);

seizeGuardianPaused

function seizeGuardianPaused() external view returns (bool);

claimComp

function claimComp(address holder) external;

claimComp

function claimComp(address holder, address[] memory cTokens) external;

compSpeeds

function compSpeeds(address) external view returns (uint256);

compSupplySpeeds

function compSupplySpeeds(address) external view returns (uint256);

compBorrowSpeeds

function compBorrowSpeeds(address) external view returns (uint256);

compSupplyState

function compSupplyState(address) external view returns (CompMarketState memory);

compBorrowState

function compBorrowState(address) external view returns (CompMarketState memory);

getCompAddress

function getCompAddress() external view returns (address);

_setPriceOracle

function _setPriceOracle(address newOracle) external returns (uint256);

_setMintPaused

function _setMintPaused(ICToken cToken, bool state) external returns (bool);

_setBorrowPaused

function _setBorrowPaused(ICToken cToken, bool state) external returns (bool);

_setCollateralFactor

function _setCollateralFactor(ICToken cToken, uint256 newCollateralFactorMantissa) external returns (uint256);

_setCompSpeeds

function _setCompSpeeds(ICToken[] memory cTokens, uint256[] memory supplySpeeds, uint256[] memory borrowSpeeds)
    external;

Structs

CompMarketState

struct CompMarketState {
    uint224 index;
    uint32 block;
}

IInterestRateModel

Git Source

Functions

getSupplyRate

function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa)
    external
    view
    returns (uint256);

getBorrowRate

function getBorrowRate(uint256 cash, uint256 borrows, uint256 reserves) external view returns (uint256);

ICToken

Git Source

Functions

isCToken

function isCToken() external returns (bool);

transfer

function transfer(address dst, uint256 amount) external returns (bool);

transferFrom

function transferFrom(address src, address dst, uint256 amount) external returns (bool);

approve

function approve(address spender, uint256 amount) external returns (bool);

allowance

function allowance(address owner, address spender) external view returns (uint256);

balanceOf

function balanceOf(address owner) external view returns (uint256);

balanceOfUnderlying

function balanceOfUnderlying(address owner) external returns (uint256);

getAccountSnapshot

function getAccountSnapshot(address account) external view returns (uint256, uint256, uint256, uint256);

borrowRatePerBlock

function borrowRatePerBlock() external view returns (uint256);

supplyRatePerBlock

function supplyRatePerBlock() external view returns (uint256);

totalBorrowsCurrent

function totalBorrowsCurrent() external returns (uint256);

borrowBalanceCurrent

function borrowBalanceCurrent(address account) external returns (uint256);

borrowBalanceStored

function borrowBalanceStored(address account) external view returns (uint256);

exchangeRateCurrent

function exchangeRateCurrent() external returns (uint256);

exchangeRateStored

function exchangeRateStored() external view returns (uint256);

getCash

function getCash() external view returns (uint256);

seize

function seize(address liquidator, address borrower, uint256 seizeTokens) external returns (uint256);

borrowRate

function borrowRate() external returns (uint256);

borrowIndex

function borrowIndex() external view returns (uint256);

borrow

function borrow(uint256) external returns (uint256);

repayBorrow

function repayBorrow(uint256) external returns (uint256);

repayBorrowBehalf

function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);

liquidateBorrow

function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external returns (uint256);

underlying

function underlying() external view returns (address);

mint

function mint(uint256) external returns (uint256);

redeemUnderlying

function redeemUnderlying(uint256) external returns (uint256);

accrueInterest

function accrueInterest() external returns (uint256);

totalSupply

function totalSupply() external view returns (uint256);

totalBorrows

function totalBorrows() external view returns (uint256);

accrualBlockNumber

function accrualBlockNumber() external view returns (uint256);

totalReserves

function totalReserves() external view returns (uint256);

interestRateModel

function interestRateModel() external view returns (IInterestRateModel);

reserveFactorMantissa

function reserveFactorMantissa() external view returns (uint256);

_setPendingAdmin

Admin Functions **

function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);

_acceptAdmin

function _acceptAdmin() external returns (uint256);

_setComptroller

function _setComptroller(IComptroller newComptroller) external returns (uint256);

_setReserveFactor

function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);

_reduceReserves

function _reduceReserves(uint256 reduceAmount) external returns (uint256);

_setInterestRateModel

function _setInterestRateModel(IInterestRateModel newInterestRateModel) external returns (uint256);

ICEther

Git Source

Inherits: ICToken

Functions

mint

function mint() external payable;

repayBorrow

function repayBorrow() external payable;

ICompoundOracle

Git Source

Functions

getUnderlyingPrice

function getUnderlyingPrice(address) external view returns (uint256);

IInterestRatesManager

Git Source

Functions

updateP2PIndexes

function updateP2PIndexes(address _marketAddress) external;

IMorpho

Git Source

Functions

CTOKEN_DECIMALS

STORAGE ///

function CTOKEN_DECIMALS() external view returns (uint8);

MAX_BASIS_POINTS

function MAX_BASIS_POINTS() external view returns (uint16);

WAD

function WAD() external view returns (uint256);

isClaimRewardsPaused

function isClaimRewardsPaused() external view returns (bool);

defaultMaxGasForMatching

function defaultMaxGasForMatching() external view returns (Types.MaxGasForMatching memory);

maxSortedUsers

function maxSortedUsers() external view returns (uint256);

dustThreshold

function dustThreshold() external view returns (uint256);

supplyBalanceInOf

function supplyBalanceInOf(address, address) external view returns (Types.SupplyBalance memory);

borrowBalanceInOf

function borrowBalanceInOf(address, address) external view returns (Types.BorrowBalance memory);

enteredMarkets

function enteredMarkets(address, uint256) external view returns (address);

deltas

function deltas(address) external view returns (Types.Delta memory);

marketParameters

function marketParameters(address) external view returns (Types.MarketParameters memory);

marketPauseStatus

function marketPauseStatus(address) external view returns (Types.MarketPauseStatus memory);

p2pDisabled

function p2pDisabled(address) external view returns (bool);

p2pSupplyIndex

function p2pSupplyIndex(address) external view returns (uint256);

p2pBorrowIndex

function p2pBorrowIndex(address) external view returns (uint256);

lastPoolIndexes

function lastPoolIndexes(address) external view returns (Types.LastPoolIndexes memory);

marketStatus

function marketStatus(address) external view returns (Types.MarketStatus memory);

comptroller

function comptroller() external view returns (IComptroller);

interestRatesManager

function interestRatesManager() external view returns (IInterestRatesManager);

rewardsManager

function rewardsManager() external view returns (IRewardsManager);

positionsManager

function positionsManager() external view returns (IPositionsManager);

incentivesVault

function incentivesVault() external view returns (address);

treasuryVault

function treasuryVault() external view returns (address);

cEth

function cEth() external view returns (address);

wEth

function wEth() external view returns (address);

getEnteredMarkets

GETTERS ///

function getEnteredMarkets(address _user) external view returns (address[] memory);

getAllMarkets

function getAllMarkets() external view returns (address[] memory);

getHead

function getHead(address _poolToken, Types.PositionType _positionType) external view returns (address head);

getNext

function getNext(address _poolToken, Types.PositionType _positionType, address _user)
    external
    view
    returns (address next);

setMaxSortedUsers

GOVERNANCE ///

function setMaxSortedUsers(uint256 _newMaxSortedUsers) external;

setDefaultMaxGasForMatching

function setDefaultMaxGasForMatching(Types.MaxGasForMatching memory _maxGasForMatching) external;

setRewardsManager

function setRewardsManager(address _rewardsManagerAddress) external;

setPositionsManager

function setPositionsManager(IPositionsManager _positionsManager) external;

setInterestRatesManager

function setInterestRatesManager(IInterestRatesManager _interestRatesManager) external;

setTreasuryVault

function setTreasuryVault(address _treasuryVault) external;

setDustThreshold

function setDustThreshold(uint256 _dustThreshold) external;

setIsP2PDisabled

function setIsP2PDisabled(address _poolToken, bool _isP2PDisabled) external;

setReserveFactor

function setReserveFactor(address _poolToken, uint256 _newReserveFactor) external;

setP2PIndexCursor

function setP2PIndexCursor(address _poolToken, uint16 _p2pIndexCursor) external;

setIsPausedForAllMarkets

function setIsPausedForAllMarkets(bool _isPaused) external;

setIsClaimRewardsPaused

function setIsClaimRewardsPaused(bool _isPaused) external;

setIsSupplyPaused

function setIsSupplyPaused(address _poolToken, bool _isPaused) external;

setIsBorrowPaused

function setIsBorrowPaused(address _poolToken, bool _isPaused) external;

setIsWithdrawPaused

function setIsWithdrawPaused(address _poolToken, bool _isPaused) external;

setIsRepayPaused

function setIsRepayPaused(address _poolToken, bool _isPaused) external;

setIsLiquidateCollateralPaused

function setIsLiquidateCollateralPaused(address _poolToken, bool _isPaused) external;

setIsLiquidateBorrowPaused

function setIsLiquidateBorrowPaused(address _poolToken, bool _isPaused) external;

claimToTreasury

function claimToTreasury(address[] calldata _poolTokens, uint256[] calldata _amounts) external;

createMarket

function createMarket(address _poolToken, Types.MarketParameters calldata _params) external;

supply

USERS ///

function supply(address _poolToken, uint256 _amount) external;

supply

function supply(address _poolToken, address _onBehalf, uint256 _amount) external;

supply

function supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) external;

borrow

function borrow(address _poolToken, uint256 _amount) external;

borrow

function borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;

withdraw

function withdraw(address _poolToken, uint256 _amount) external;

withdraw

function withdraw(address _poolToken, uint256 _amount, address _receiver) external;

repay

function repay(address _poolToken, uint256 _amount) external;

repay

function repay(address _poolToken, address _onBehalf, uint256 _amount) external;

liquidate

function liquidate(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external;

claimRewards

function claimRewards(address[] calldata _cTokenAddresses, bool _tradeForMorphoToken)
    external
    returns (uint256 claimedAmount);

IOracle

Git Source

Functions

consult

function consult(uint256 _amountIn) external returns (uint256);

IPositionsManager

Git Source

Functions

supplyLogic

function supplyLogic(
    address _poolToken,
    address _supplier,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) external;

borrowLogic

function borrowLogic(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;

withdrawLogic

function withdrawLogic(
    address _poolToken,
    uint256 _amount,
    address _supplier,
    address _receiver,
    uint256 _maxGasForMatching
) external;

repayLogic

function repayLogic(
    address _poolToken,
    address _repayer,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) external;

liquidateLogic

function liquidateLogic(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external;

increaseP2PDeltasLogic

function increaseP2PDeltasLogic(address _poolToken, uint256 _amount) external;

IRewardsManager

Git Source

Functions

initialize

function initialize(address _morpho) external;

claimRewards

function claimRewards(address[] calldata, address) external returns (uint256);

userUnclaimedCompRewards

function userUnclaimedCompRewards(address) external view returns (uint256);

compSupplierIndex

function compSupplierIndex(address, address) external view returns (uint256);

compBorrowerIndex

function compBorrowerIndex(address, address) external view returns (uint256);

getLocalCompSupplyState

function getLocalCompSupplyState(address _cTokenAddress) external view returns (IComptroller.CompMarketState memory);

getLocalCompBorrowState

function getLocalCompBorrowState(address _cTokenAddress) external view returns (IComptroller.CompMarketState memory);

accrueUserSupplyUnclaimedRewards

function accrueUserSupplyUnclaimedRewards(address, address, uint256) external;

accrueUserBorrowUnclaimedRewards

function accrueUserBorrowUnclaimedRewards(address, address, uint256) external;

IWETH

Git Source

Functions

deposit

function deposit() external payable;

withdraw

function withdraw(uint256) external;

Contents

Contents

ILens

Git Source

Functions

MAX_BASIS_POINTS

STORAGE ///

function MAX_BASIS_POINTS() external view returns (uint256);

WAD

function WAD() external view returns (uint256);

morpho

function morpho() external view returns (IMorpho);

comptroller

function comptroller() external view returns (IComptroller);

rewardsManager

function rewardsManager() external view returns (IRewardsManager);

getTotalSupply

GENERAL ///

function getTotalSupply()
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount, uint256 totalSupplyAmount);

getTotalBorrow

function getTotalBorrow()
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount, uint256 totalBorrowAmount);

isMarketCreated

MARKETS ///

function isMarketCreated(address _poolToken) external view returns (bool);

isMarketCreatedAndNotPaused

Deprecated.

function isMarketCreatedAndNotPaused(address _poolToken) external view returns (bool);

isMarketCreatedAndNotPausedNorPartiallyPaused

Deprecated.

function isMarketCreatedAndNotPausedNorPartiallyPaused(address _poolToken) external view returns (bool);

getAllMarkets

function getAllMarkets() external view returns (address[] memory marketsCreated_);

getMainMarketData

function getMainMarketData(address _poolToken)
    external
    view
    returns (
        uint256 avgSupplyRatePerBlock,
        uint256 avgBorrowRatePerBlock,
        uint256 p2pSupplyAmount,
        uint256 p2pBorrowAmount,
        uint256 poolSupplyAmount,
        uint256 poolBorrowAmount
    );

getAdvancedMarketData

function getAdvancedMarketData(address _poolToken)
    external
    view
    returns (Types.Indexes memory indexes, uint32 lastUpdateBlockNumber, uint256 p2pSupplyDelta, uint256 p2pBorrowDelta);

getMarketConfiguration

function getMarketConfiguration(address _poolToken)
    external
    view
    returns (
        address underlying,
        bool isCreated,
        bool p2pDisabled,
        bool isPaused,
        bool isPartiallyPaused,
        uint16 reserveFactor,
        uint16 p2pIndexCursor,
        uint256 collateralFactor
    );

getMarketPauseStatus

function getMarketPauseStatus(address _poolToken) external view returns (Types.MarketPauseStatus memory);

getTotalMarketSupply

function getTotalMarketSupply(address _poolToken)
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

getTotalMarketBorrow

function getTotalMarketBorrow(address _poolToken)
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

getCurrentP2PSupplyIndex

INDEXES ///

function getCurrentP2PSupplyIndex(address _poolToken) external view returns (uint256);

getCurrentP2PBorrowIndex

function getCurrentP2PBorrowIndex(address _poolToken) external view returns (uint256);

getCurrentPoolIndexes

function getCurrentPoolIndexes(address _poolToken)
    external
    view
    returns (uint256 currentPoolSupplyIndex, uint256 currentPoolBorrowIndex);

getIndexes

function getIndexes(address _poolToken, bool _computeUpdatedIndexes)
    external
    view
    returns (Types.Indexes memory indexes);

getEnteredMarkets

USERS ///

function getEnteredMarkets(address _user) external view returns (address[] memory enteredMarkets);

getUserHealthFactor

function getUserHealthFactor(address _user, address[] calldata _updatedMarkets) external view returns (uint256);

getUserBalanceStates

function getUserBalanceStates(address _user, address[] calldata _updatedMarkets)
    external
    view
    returns (uint256 collateralValue, uint256 debtValue, uint256 maxDebtValue);

getCurrentSupplyBalanceInOf

function getCurrentSupplyBalanceInOf(address _poolToken, address _user)
    external
    view
    returns (uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

getCurrentBorrowBalanceInOf

function getCurrentBorrowBalanceInOf(address _poolToken, address _user)
    external
    view
    returns (uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

getUserMaxCapacitiesForAsset

function getUserMaxCapacitiesForAsset(address _user, address _poolToken)
    external
    view
    returns (uint256 withdrawable, uint256 borrowable);

getUserHypotheticalBalanceStates

function getUserHypotheticalBalanceStates(
    address _user,
    address _poolToken,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) external view returns (uint256 debtValue, uint256 maxDebtValue);

getUserLiquidityDataForAsset

function getUserLiquidityDataForAsset(
    address _user,
    address _poolToken,
    bool _computeUpdatedIndexes,
    ICompoundOracle _oracle
) external view returns (Types.AssetLiquidityData memory assetData);

isLiquidatable

function isLiquidatable(address _user, address[] memory _updatedMarkets) external view returns (bool);

isLiquidatable

function isLiquidatable(address _user, address _poolToken, address[] memory _updatedMarkets)
    external
    view
    returns (bool);

computeLiquidationRepayAmount

function computeLiquidationRepayAmount(
    address _user,
    address _poolTokenBorrowed,
    address _poolTokenCollateral,
    address[] calldata _updatedMarkets
) external view returns (uint256 toRepay);

getNextUserSupplyRatePerBlock

RATES ///

function getNextUserSupplyRatePerBlock(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextSupplyRatePerBlock, uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

getNextUserBorrowRatePerBlock

function getNextUserBorrowRatePerBlock(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextBorrowRatePerBlock, uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

getCurrentUserSupplyRatePerBlock

function getCurrentUserSupplyRatePerBlock(address _poolToken, address _user) external view returns (uint256);

getCurrentUserBorrowRatePerBlock

function getCurrentUserBorrowRatePerBlock(address _poolToken, address _user) external view returns (uint256);

getAverageSupplyRatePerBlock

function getAverageSupplyRatePerBlock(address _poolToken)
    external
    view
    returns (uint256 avgSupplyRatePerBlock, uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

getAverageBorrowRatePerBlock

function getAverageBorrowRatePerBlock(address _poolToken)
    external
    view
    returns (uint256 avgBorrowRatePerBlock, uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

getRatesPerBlock

function getRatesPerBlock(address _poolToken)
    external
    view
    returns (uint256 p2pSupplyRate, uint256 p2pBorrowRate, uint256 poolSupplyRate, uint256 poolBorrowRate);

getUserUnclaimedRewards

REWARDS ///

function getUserUnclaimedRewards(address[] calldata _poolTokens, address _user)
    external
    view
    returns (uint256 unclaimedRewards);

getAccruedSupplierComp

function getAccruedSupplierComp(address _supplier, address _poolToken, uint256 _balance)
    external
    view
    returns (uint256);

getAccruedBorrowerComp

function getAccruedBorrowerComp(address _borrower, address _poolToken, uint256 _balance)
    external
    view
    returns (uint256);

getAccruedSupplierComp

function getAccruedSupplierComp(address _supplier, address _poolToken) external view returns (uint256);

getAccruedBorrowerComp

function getAccruedBorrowerComp(address _borrower, address _poolToken) external view returns (uint256);

getCurrentCompSupplyIndex

function getCurrentCompSupplyIndex(address _poolToken) external view returns (uint256);

getCurrentCompBorrowIndex

function getCurrentCompBorrowIndex(address _poolToken) external view returns (uint256);

ILensExtension

Git Source

Functions

morpho

function morpho() external view returns (IMorpho);

getUserUnclaimedRewards

function getUserUnclaimedRewards(address[] calldata _poolTokens, address _user)
    external
    view
    returns (uint256 unclaimedRewards);

getAccruedSupplierComp

function getAccruedSupplierComp(address _supplier, address _poolToken, uint256 _balance)
    external
    view
    returns (uint256);

getAccruedBorrowerComp

function getAccruedBorrowerComp(address _borrower, address _poolToken, uint256 _balance)
    external
    view
    returns (uint256);

getAccruedSupplierComp

function getAccruedSupplierComp(address _supplier, address _poolToken) external view returns (uint256);

getAccruedBorrowerComp

function getAccruedBorrowerComp(address _borrower, address _poolToken) external view returns (uint256);

getCurrentCompSupplyIndex

function getCurrentCompSupplyIndex(address _poolToken) external view returns (uint256);

getCurrentCompBorrowIndex

function getCurrentCompBorrowIndex(address _poolToken) external view returns (uint256);

IndexesLens

Git Source

Inherits: LensStorage

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol market indexes & rates.

Functions

getCurrentP2PSupplyIndex

EXTERNAL ///

Returns the updated peer-to-peer supply index.

function getCurrentP2PSupplyIndex(address _poolToken) external view returns (uint256 p2pSupplyIndex);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
p2pSupplyIndexuint256The virtually updated peer-to-peer supply index.

getCurrentP2PBorrowIndex

Returns the updated peer-to-peer borrow index.

function getCurrentP2PBorrowIndex(address _poolToken) external view returns (uint256 p2pBorrowIndex);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
p2pBorrowIndexuint256The virtually updated peer-to-peer borrow index.

getIndexes

Returns the most up-to-date or virtually updated peer-to-peer and pool indexes.

If not virtually updated, the indexes returned are those used by Morpho for non-updated markets during the liquidity check.

function getIndexes(address _poolToken, bool _updated) external view returns (Types.Indexes memory indexes);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_updatedboolWhether to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
indexesTypes.IndexesThe given market's virtually updated indexes.

getCurrentPoolIndexes

Returns the virtually updated pool indexes of a given market.

Mimicks CToken.accrueInterest's calculations, without writing to the storage.

function getCurrentPoolIndexes(address _poolToken)
    external
    view
    returns (uint256 poolSupplyIndex, uint256 poolBorrowIndex);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
poolSupplyIndexuint256The supply index.
poolBorrowIndexuint256The borrow index.

_getIndexes

Returns the most up-to-date or virtually updated peer-to-peer and pool indexes.

If not virtually updated, the indexes returned are those used by Morpho for non-updated markets during the liquidity check.

function _getIndexes(address _poolToken, bool _updated)
    internal
    view
    returns (Types.Delta memory delta, Types.Indexes memory indexes);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_updatedboolWhether to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
deltaTypes.DeltaThe given market's deltas.
indexesTypes.IndexesThe given market's updated indexes.

_accruePoolInterests

Returns the virtually updated pool indexes of a given market.

Mimicks CToken.accrueInterest's calculations, without writing to the storage.

function _accruePoolInterests(ICToken _poolToken)
    internal
    view
    returns (uint256 poolSupplyIndex, uint256 poolBorrowIndex, PoolInterestsVars memory vars);

Parameters

NameTypeDescription
_poolTokenICTokenThe address of the market.

Returns

NameTypeDescription
poolSupplyIndexuint256The supply index.
poolBorrowIndexuint256The borrow index.
varsPoolInterestsVars

_computeP2PIndexes

Returns the most up-to-date or virtually updated peer-to-peer indexes.

If not virtually updated, the indexes returned are those used by Morpho for non-updated markets during the liquidity check.

function _computeP2PIndexes(
    address _poolToken,
    bool _updated,
    uint256 _poolSupplyIndex,
    uint256 _poolBorrowIndex,
    Types.Delta memory _delta,
    Types.LastPoolIndexes memory _lastPoolIndexes
)
    internal
    view
    returns (uint256 _p2pSupplyIndex, uint256 _p2pBorrowIndex, Types.MarketParameters memory marketParameters);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_updatedboolWhether to compute virtually updated peer-to-peer indexes.
_poolSupplyIndexuint256The underlying pool supply index.
_poolBorrowIndexuint256The underlying pool borrow index.
_deltaTypes.DeltaThe given market's deltas.
_lastPoolIndexesTypes.LastPoolIndexesThe last pool indexes stored on Morpho.

Returns

NameTypeDescription
_p2pSupplyIndexuint256The given market's peer-to-peer supply index.
_p2pBorrowIndexuint256The given market's peer-to-peer borrow index.
marketParametersTypes.MarketParameters

Structs

PoolInterestsVars

INTERNAL ///

struct PoolInterestsVars {
    uint256 cash;
    uint256 totalBorrows;
    uint256 totalReserves;
    uint256 reserveFactorMantissa;
}

Lens

Git Source

Inherits: RewardsLens

Author: Morpho Labs.

This contract exposes an API to query on-chain data related to the Morpho Protocol, its markets and its users.

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

constructor(address _lensExtension) LensStorage(_lensExtension);

Parameters

NameTypeDescription
_lensExtensionaddressThe address of the Lens extension.

getTotalSupply

EXTERNAL ///

Computes and returns the total distribution of supply through Morpho, using virtually updated indexes.

function getTotalSupply()
    external
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount, uint256 totalSupplyAmount);

Returns

NameTypeDescription
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in USD, 18 decimals).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in USD, 18 decimals).
totalSupplyAmountuint256The total amount supplied through Morpho (in USD, 18 decimals).

getTotalBorrow

Computes and returns the total distribution of borrows through Morpho, using virtually updated indexes.

function getTotalBorrow()
    external
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount, uint256 totalBorrowAmount);

Returns

NameTypeDescription
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in USD, 18 decimals).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in USD, 18 decimals).
totalBorrowAmountuint256The total amount borrowed through Morpho (in USD, 18 decimals).

LensExtension

Git Source

Inherits: ILensExtension

Author: Morpho Labs.

This contract is an extension of the Lens. It should be deployed before the Lens, as the Lens depends on its address to extends its functionalities.

State Variables

morpho

STORAGE ///

IMorpho public immutable morpho;

comptroller

IComptroller internal immutable comptroller;

rewardsManager

IRewardsManager internal immutable rewardsManager;

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

constructor(address _morpho);

Parameters

NameTypeDescription
_morphoaddressThe address of the main Morpho contract.

getUserUnclaimedRewards

EXTERNAL ///

Returns the unclaimed COMP rewards for the given cToken addresses.

function getUserUnclaimedRewards(address[] calldata _poolTokens, address _user)
    external
    view
    returns (uint256 unclaimedRewards);

Parameters

NameTypeDescription
_poolTokensaddress[]The cToken addresses for which to compute the rewards.
_useraddressThe address of the user.

getAccruedSupplierComp

PUBLIC ///

Returns the accrued COMP rewards of a user since the last update.

function getAccruedSupplierComp(address _supplier, address _poolToken) public view returns (uint256);

Parameters

NameTypeDescription
_supplieraddressThe address of the supplier.
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getAccruedBorrowerComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedBorrowerComp(address _borrower, address _poolToken) public view returns (uint256);

Parameters

NameTypeDescription
_borroweraddressThe address of the borrower.
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getAccruedSupplierComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedSupplierComp(address _supplier, address _poolToken, uint256 _balance)
    public
    view
    returns (uint256);

Parameters

NameTypeDescription
_supplieraddressThe address of the supplier.
_poolTokenaddressThe cToken address.
_balanceuint256The user balance of tokens in the distribution.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getAccruedBorrowerComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedBorrowerComp(address _borrower, address _poolToken, uint256 _balance)
    public
    view
    returns (uint256);

Parameters

NameTypeDescription
_borroweraddressThe address of the borrower.
_poolTokenaddressThe cToken address.
_balanceuint256The user balance of tokens in the distribution.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getCurrentCompSupplyIndex

Returns the updated COMP supply index.

function getCurrentCompSupplyIndex(address _poolToken) public view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The updated COMP supply index.

getCurrentCompBorrowIndex

Returns the updated COMP borrow index.

function getCurrentCompBorrowIndex(address _poolToken) public view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The updated COMP borrow index.

Errors

InvalidCToken

ERRORS ///

Thrown when an invalid cToken address is passed to claim rewards.

error InvalidCToken();

LensStorage

Git Source

Inherits: ILens, Initializable

Author: Morpho Labs.

Base layer to the Morpho Protocol Lens, managing the upgradeable storage layout.

State Variables

MAX_BASIS_POINTS

CONSTANTS ///

uint256 public constant MAX_BASIS_POINTS = 100_00;

WAD

uint256 public constant WAD = 1e18;

morpho

IMMUTABLES ///

IMorpho public immutable morpho;

comptroller

IComptroller public immutable comptroller;

rewardsManager

IRewardsManager public immutable rewardsManager;

lensExtension

ILensExtension internal immutable lensExtension;

deprecatedMorpho

STORAGE ///

address private deprecatedMorpho;

deprecatedComptroller

address private deprecatedComptroller;

deprecatedRewardsManager

address private deprecatedRewardsManager;

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

constructor(address _lensExtension);

Parameters

NameTypeDescription
_lensExtensionaddressThe address of the Lens extension.

MarketsLens

Git Source

Inherits: RatesLens

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol markets.

Functions

isMarketCreated

EXTERNAL ///

Checks if a market is created.

function isMarketCreated(address _poolToken) external view returns (bool);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
<none>booltrue if the market is created and not paused, otherwise false.

isMarketCreatedAndNotPaused

Deprecated.

function isMarketCreatedAndNotPaused(address) external pure returns (bool);

isMarketCreatedAndNotPausedNorPartiallyPaused

Deprecated.

function isMarketCreatedAndNotPausedNorPartiallyPaused(address) external pure returns (bool);

getAllMarkets

Returns all created markets.

function getAllMarkets() external view returns (address[] memory marketsCreated);

Returns

NameTypeDescription
marketsCreatedaddress[]The list of market addresses.

getMainMarketData

For a given market, returns the average supply/borrow rates and amounts of underlying asset supplied and borrowed through Morpho, on the underlying pool and matched peer-to-peer.

The returned values are not updated.

function getMainMarketData(address _poolToken)
    external
    view
    returns (
        uint256 avgSupplyRatePerBlock,
        uint256 avgBorrowRatePerBlock,
        uint256 p2pSupplyAmount,
        uint256 p2pBorrowAmount,
        uint256 poolSupplyAmount,
        uint256 poolBorrowAmount
    );

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get main data.

Returns

NameTypeDescription
avgSupplyRatePerBlockuint256The average supply rate experienced on the given market.
avgBorrowRatePerBlockuint256The average borrow rate experienced on the given market.
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

getAdvancedMarketData

Returns non-updated indexes, the block at which they were last updated and the total deltas of a given market.

function getAdvancedMarketData(address _poolToken)
    external
    view
    returns (Types.Indexes memory indexes, uint32 lastUpdateBlockNumber, uint256 p2pSupplyDelta, uint256 p2pBorrowDelta);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get advanced data.

Returns

NameTypeDescription
indexesTypes.IndexesThe given market's virtually updated indexes.
lastUpdateBlockNumberuint32The block number at which pool indexes were last updated.
p2pSupplyDeltauint256The total supply delta (in underlying).
p2pBorrowDeltauint256The total borrow delta (in underlying).

getMarketConfiguration

Returns the given market's configuration.

function getMarketConfiguration(address _poolToken)
    external
    view
    returns (
        address underlying,
        bool isCreated,
        bool p2pDisabled,
        bool isPaused,
        bool isPartiallyPaused,
        uint16 reserveFactor,
        uint16 p2pIndexCursor,
        uint256 collateralFactor
    );

Returns

NameTypeDescription
underlyingaddressThe underlying token address.
isCreatedboolWhether the market is created or not.
p2pDisabledboolWhether the peer-to-peer market is enabled or not.
isPausedboolDeprecated.
isPartiallyPausedboolDeprecated.
reserveFactoruint16The reserve factor applied to this market.
p2pIndexCursoruint16The p2p index cursor applied to this market.
collateralFactoruint256The pool collateral factor also used by Morpho.

getMarketPauseStatus

Returns the given market's pause statuses.

function getMarketPauseStatus(address _poolToken) external view returns (Types.MarketPauseStatus memory);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to get pause statuses.

Returns

NameTypeDescription
<none>Types.MarketPauseStatusThe market status struct.

getTotalMarketSupply

PUBLIC ///

Computes and returns the total distribution of supply for a given market, using virtually updated indexes.

function getTotalMarketSupply(address _poolToken)
    public
    view
    returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

getTotalMarketBorrow

Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.

function getTotalMarketBorrow(address _poolToken)
    public
    view
    returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

Returns

NameTypeDescription
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

RatesLens

Git Source

Inherits: UsersLens

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol users and their positions.

Functions

getNextUserSupplyRatePerBlock

EXTERNAL ///

Returns the supply rate per block experienced on a market after having supplied the given amount on behalf of the given user.

Note: the returned supply rate is a low estimate: when supplying through Morpho-Compound, a supplier could be matched more than once instantly or later and thus benefit from a higher supply rate.

function getNextUserSupplyRatePerBlock(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextSupplyRatePerBlock, uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe address of the user on behalf of whom to supply.
_amountuint256The amount to supply.

Returns

NameTypeDescription
nextSupplyRatePerBlockuint256An approximation of the next supply rate per block experienced after having supplied (in wad).
balanceOnPooluint256The total balance supplied on pool after having supplied (in underlying).
balanceInP2Puint256The total balance matched peer-to-peer after having supplied (in underlying).
totalBalanceuint256The total balance supplied through Morpho (in underlying).

getNextUserBorrowRatePerBlock

Returns the borrow rate per block experienced on a market after having supplied the given amount on behalf of the given user.

Note: the returned borrow rate is a high estimate: when borrowing through Morpho-Compound, a borrower could be matched more than once instantly or later and thus benefit from a lower borrow rate.

function getNextUserBorrowRatePerBlock(address _poolToken, address _user, uint256 _amount)
    external
    view
    returns (uint256 nextBorrowRatePerBlock, uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe address of the user on behalf of whom to borrow.
_amountuint256The amount to borrow.

Returns

NameTypeDescription
nextBorrowRatePerBlockuint256An approximation of the next borrow rate per block experienced after having supplied (in wad).
balanceOnPooluint256The total balance supplied on pool after having supplied (in underlying).
balanceInP2Puint256The total balance matched peer-to-peer after having supplied (in underlying).
totalBalanceuint256The total balance supplied through Morpho (in underlying).

getCurrentUserSupplyRatePerBlock

Returns the supply rate per block a given user is currently experiencing on a given market.

function getCurrentUserSupplyRatePerBlock(address _poolToken, address _user)
    external
    view
    returns (uint256 supplyRatePerBlock);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to compute the supply rate per block for.

Returns

NameTypeDescription
supplyRatePerBlockuint256The supply rate per block the user is currently experiencing (in wad).

getCurrentUserBorrowRatePerBlock

Returns the borrow rate per block a given user is currently experiencing on a given market.

function getCurrentUserBorrowRatePerBlock(address _poolToken, address _user)
    external
    view
    returns (uint256 borrowRatePerBlock);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to compute the borrow rate per block for.

Returns

NameTypeDescription
borrowRatePerBlockuint256The borrow rate per block the user is currently experiencing (in wad).

getAverageSupplyRatePerBlock

PUBLIC ///

Computes and returns the current supply rate per block experienced on average on a given market.

function getAverageSupplyRatePerBlock(address _poolToken)
    public
    view
    returns (uint256 avgSupplyRatePerBlock, uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.

Returns

NameTypeDescription
avgSupplyRatePerBlockuint256The market's average supply rate per block (in wad).
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

getAverageBorrowRatePerBlock

Computes and returns the current average borrow rate per block experienced on a given market.

function getAverageBorrowRatePerBlock(address _poolToken)
    public
    view
    returns (uint256 avgBorrowRatePerBlock, uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.

Returns

NameTypeDescription
avgBorrowRatePerBlockuint256The market's average borrow rate per block (in wad).
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

getRatesPerBlock

Computes and returns peer-to-peer and pool rates for a specific market.

Note: prefer using getAverageSupplyRatePerBlock & getAverageBorrowRatePerBlock to get the actual experienced supply/borrow rate.

function getRatesPerBlock(address _poolToken) external view returns (uint256, uint256, uint256, uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.

Returns

NameTypeDescription
<none>uint256p2pSupplyRate The market's peer-to-peer supply rate per block (in wad).
<none>uint256p2pBorrowRate The market's peer-to-peer borrow rate per block (in wad).
<none>uint256poolSupplyRate The market's pool supply rate per block (in wad).
<none>uint256poolBorrowRate The market's pool borrow rate per block (in wad).

_getRatesPerBlock

Computes and returns peer-to-peer and pool rates for a specific market.

function _getRatesPerBlock(
    address _poolToken,
    uint256 _suppliedOnPool,
    uint256 _borrowedFromPool,
    uint256 _repaidOnPool,
    uint256 _withdrawnFromPool
)
    internal
    view
    returns (uint256 p2pSupplyRate, uint256 p2pBorrowRate, uint256 poolSupplyRate, uint256 poolBorrowRate);

Parameters

NameTypeDescription
_poolTokenaddressThe market address.
_suppliedOnPooluint256The amount hypothetically supplied to the underlying's pool (in underlying).
_borrowedFromPooluint256The amount hypothetically borrowed from the underlying's pool (in underlying).
_repaidOnPooluint256The amount hypothetically repaid to the underlying's pool (in underlying).
_withdrawnFromPooluint256The amount hypothetically withdrawn from the underlying's pool (in underlying).

Returns

NameTypeDescription
p2pSupplyRateuint256The market's peer-to-peer supply rate per block (in wad).
p2pBorrowRateuint256The market's peer-to-peer borrow rate per block (in wad).
poolSupplyRateuint256The market's pool supply rate per block (in wad).
poolBorrowRateuint256The market's pool borrow rate per block (in wad).

_getMarketSupply

Computes and returns the total distribution of supply for a given market, using virtually updated indexes.

function _getMarketSupply(
    address _poolToken,
    uint256 _p2pSupplyIndex,
    uint256 _poolSupplyIndex,
    Types.Delta memory _delta
) internal view returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.
_p2pSupplyIndexuint256The given market's peer-to-peer supply index.
_poolSupplyIndexuint256The given market's pool supply index.
_deltaTypes.DeltaThe given market's deltas.

Returns

NameTypeDescription
p2pSupplyAmountuint256The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
poolSupplyAmountuint256The total supplied amount on the underlying pool, adding the supply delta (in underlying).

_getMarketBorrow

Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.

function _getMarketBorrow(
    address _poolToken,
    uint256 _p2pBorrowIndex,
    uint256 _poolBorrowIndex,
    Types.Delta memory _delta
) internal view returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.
_p2pBorrowIndexuint256The given market's peer-to-peer borrow index.
_poolBorrowIndexuint256The given market's borrow index.
_deltaTypes.DeltaThe given market's deltas.

Returns

NameTypeDescription
p2pBorrowAmountuint256The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
poolBorrowAmountuint256The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).

_getUserSupplyRatePerBlock

Returns the supply rate per block experienced on a market based on a given position distribution. The calculation takes into account the change in pool rates implied by an hypothetical supply and/or repay.

function _getUserSupplyRatePerBlock(
    address _poolToken,
    uint256 _balanceInP2P,
    uint256 _balanceOnPool,
    uint256 _suppliedOnPool,
    uint256 _repaidToPool
) internal view returns (uint256, uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_balanceInP2Puint256The amount of balance matched peer-to-peer (in a unit common to _balanceOnPool).
_balanceOnPooluint256The amount of balance supplied on pool (in a unit common to _balanceInP2P).
_suppliedOnPooluint256The amount hypothetically supplied on pool (in underlying).
_repaidToPooluint256The amount hypothetically repaid to the pool (in underlying).

Returns

NameTypeDescription
<none>uint256The supply rate per block experienced by the given position (in wad).
<none>uint256The sum of peer-to-peer & pool balances.

_getUserBorrowRatePerBlock

Returns the borrow rate per block experienced on a market based on a given position distribution. The calculation takes into account the change in pool rates implied by an hypothetical borrow and/or withdraw.

function _getUserBorrowRatePerBlock(
    address _poolToken,
    uint256 _balanceInP2P,
    uint256 _balanceOnPool,
    uint256 _borrowedFromPool,
    uint256 _withdrawnFromPool
) internal view returns (uint256, uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_balanceInP2Puint256The amount of balance matched peer-to-peer (in a unit common to _balanceOnPool).
_balanceOnPooluint256The amount of balance supplied on pool (in a unit common to _balanceInP2P).
_borrowedFromPooluint256The amount hypothetically borrowed from the pool (in underlying).
_withdrawnFromPooluint256The amount hypothetically withdrawn from the pool (in underlying).

Returns

NameTypeDescription
<none>uint256The borrow rate per block experienced by the given position (in wad).
<none>uint256The sum of peer-to-peer & pool balances.

_getWeightedRate

Returns the rate experienced based on a given pool & peer-to-peer distribution.

function _getWeightedRate(uint256 _p2pRate, uint256 _poolRate, uint256 _balanceInP2P, uint256 _balanceOnPool)
    internal
    pure
    returns (uint256 weightedRate, uint256 totalBalance);

Parameters

NameTypeDescription
_p2pRateuint256The peer-to-peer rate (in a unit common to _poolRate & weightedRate).
_poolRateuint256The pool rate (in a unit common to _p2pRate & weightedRate).
_balanceInP2Puint256The amount of balance matched peer-to-peer (in a unit common to _balanceOnPool).
_balanceOnPooluint256The amount of balance supplied on pool (in a unit common to _balanceInP2P).

Returns

NameTypeDescription
weightedRateuint256The rate experienced by the given distribution (in a unit common to _p2pRate & _poolRate).
totalBalanceuint256The sum of peer-to-peer & pool balances.

Errors

BorrowRateFailed

ERRORS ///

error BorrowRateFailed();

Structs

PoolRatesVars

INTERNAL ///

struct PoolRatesVars {
    Types.Delta delta;
    Types.LastPoolIndexes lastPoolIndexes;
    Types.Indexes indexes;
    Types.MarketParameters params;
}

RewardsLens

Git Source

Inherits: MarketsLens

Author: Morpho Labs.

Intermediary layer serving as proxy to lighten the bytecode weight of the Lens.

Functions

getUserUnclaimedRewards

EXTERNAL ///

Returns the unclaimed COMP rewards for the given cToken addresses.

function getUserUnclaimedRewards(address[] calldata _poolTokens, address _user) external view returns (uint256);

Parameters

NameTypeDescription
_poolTokensaddress[]The cToken addresses for which to compute the rewards.
_useraddressThe address of the user.

getAccruedSupplierComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedSupplierComp(address _supplier, address _poolToken, uint256 _balance)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
_supplieraddressThe address of the supplier.
_poolTokenaddressThe cToken address.
_balanceuint256The user balance of tokens in the distribution.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getAccruedSupplierComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedSupplierComp(address _supplier, address _poolToken) external view returns (uint256);

Parameters

NameTypeDescription
_supplieraddressThe address of the supplier.
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getAccruedBorrowerComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedBorrowerComp(address _borrower, address _poolToken, uint256 _balance)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
_borroweraddressThe address of the borrower.
_poolTokenaddressThe cToken address.
_balanceuint256The user balance of tokens in the distribution.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getAccruedBorrowerComp

Returns the accrued COMP rewards of a user since the last update.

function getAccruedBorrowerComp(address _borrower, address _poolToken) external view returns (uint256);

Parameters

NameTypeDescription
_borroweraddressThe address of the borrower.
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

getCurrentCompSupplyIndex

Returns the updated COMP supply index.

function getCurrentCompSupplyIndex(address _poolToken) external view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The updated COMP supply index.

getCurrentCompBorrowIndex

Returns the updated COMP borrow index.

function getCurrentCompBorrowIndex(address _poolToken) external view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>uint256The updated COMP borrow index.

UsersLens

Git Source

Inherits: IndexesLens

Author: Morpho Labs.

Intermediary layer exposing endpoints to query live data related to the Morpho Protocol users and their positions.

Functions

getEnteredMarkets

EXTERNAL ///

Returns all markets entered by a given user.

function getEnteredMarkets(address _user) external view returns (address[] memory enteredMarkets);

Parameters

NameTypeDescription
_useraddressThe address of the user.

Returns

NameTypeDescription
enteredMarketsaddress[]The list of markets entered by this user.

getUserMaxCapacitiesForAsset

Returns the maximum amount available to withdraw & borrow for a given user, on a given market.

function getUserMaxCapacitiesForAsset(address _user, address _poolToken)
    external
    view
    returns (uint256 withdrawable, uint256 borrowable);

Parameters

NameTypeDescription
_useraddressThe user to determine the capacities for.
_poolTokenaddressThe address of the market.

Returns

NameTypeDescription
withdrawableuint256The maximum withdrawable amount of underlying token allowed (in underlying).
borrowableuint256The maximum borrowable amount of underlying token allowed (in underlying).

computeLiquidationRepayAmount

Computes the maximum repayable amount for a potential liquidation.

function computeLiquidationRepayAmount(
    address _user,
    address _poolTokenBorrowed,
    address _poolTokenCollateral,
    address[] calldata _updatedMarkets
) external view returns (uint256 toRepay);

Parameters

NameTypeDescription
_useraddressThe potential liquidatee.
_poolTokenBorrowedaddressThe address of the market to repay.
_poolTokenCollateraladdressThe address of the market to seize.
_updatedMarketsaddress[]The list of markets of which to compute virtually updated pool and peer-to-peer indexes.

getUserHealthFactor

Computes the health factor of a given user, given a list of markets of which to compute virtually updated pool & peer-to-peer indexes.

function getUserHealthFactor(address _user, address[] calldata _updatedMarkets) external view returns (uint256);

Parameters

NameTypeDescription
_useraddressThe user of whom to get the health factor.
_updatedMarketsaddress[]The list of markets of which to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
<none>uint256The health factor of the given user (in wad).

getUserHypotheticalBalanceStates

Returns the debt value, max debt value of a given user.

function getUserHypotheticalBalanceStates(
    address _user,
    address _poolToken,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) external view returns (uint256 debtUsd, uint256 maxDebtUsd);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_poolTokenaddressThe market to hypothetically withdraw/borrow in.
_withdrawnAmountuint256The amount to hypothetically withdraw from the given market (in underlying).
_borrowedAmountuint256The amount to hypothetically borrow from the given market (in underlying).

Returns

NameTypeDescription
debtUsduint256The current debt value of the user (in wad).
maxDebtUsduint256The maximum debt value possible of the user (in wad).

getUserBalanceStates

PUBLIC ///

Returns the collateral value, debt value and max debt value of a given user.

function getUserBalanceStates(address _user, address[] calldata _updatedMarkets)
    public
    view
    returns (uint256 collateralUsd, uint256 debtUsd, uint256 maxDebtUsd);

Parameters

NameTypeDescription
_useraddressThe user to determine liquidity for.
_updatedMarketsaddress[]The list of markets of which to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
collateralUsduint256The collateral value of the user (in wad).
debtUsduint256The current debt value of the user (in wad).
maxDebtUsduint256The maximum possible debt value of the user (in wad).

getCurrentSupplyBalanceInOf

Returns the balance in underlying of a given user in a given market.

function getCurrentSupplyBalanceInOf(address _poolToken, address _user)
    public
    view
    returns (uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to determine balances of.

Returns

NameTypeDescription
balanceOnPooluint256The balance on pool of the user (in underlying).
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

getCurrentBorrowBalanceInOf

Returns the borrow balance in underlying of a given user in a given market.

function getCurrentBorrowBalanceInOf(address _poolToken, address _user)
    public
    view
    returns (uint256 balanceOnPool, uint256 balanceInP2P, uint256 totalBalance);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market.
_useraddressThe user to determine balances of.

Returns

NameTypeDescription
balanceOnPooluint256The balance on pool of the user (in underlying).
balanceInP2Puint256The balance in peer-to-peer of the user (in underlying).
totalBalanceuint256The total balance of the user (in underlying).

getUserLiquidityDataForAsset

Returns the data related to _poolToken for the _user, by optionally computing virtually updated pool and peer-to-peer indexes.

function getUserLiquidityDataForAsset(
    address _user,
    address _poolToken,
    bool _getUpdatedIndexes,
    ICompoundOracle _oracle
) public view returns (Types.AssetLiquidityData memory);

Parameters

NameTypeDescription
_useraddressThe user to determine data for.
_poolTokenaddressThe address of the market.
_getUpdatedIndexesboolWhether to compute virtually updated pool and peer-to-peer indexes.
_oracleICompoundOracleThe oracle used.

Returns

NameTypeDescription
<none>Types.AssetLiquidityDataassetData The data related to this asset.

isLiquidatable

Returns whether a liquidation can be performed on a given user.

This function checks for the user's health factor, without treating borrow positions from deprecated market as instantly liquidatable.

function isLiquidatable(address _user, address[] memory _updatedMarkets) public view returns (bool);

Parameters

NameTypeDescription
_useraddressThe address of the user to check.
_updatedMarketsaddress[]The list of markets of which to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
<none>boolwhether or not the user is liquidatable.

isLiquidatable

Returns whether a liquidation can be performed on a given user borrowing from a given market.

This function checks for the user's health factor as well as whether the given market is deprecated & the user is borrowing from it.

function isLiquidatable(address _user, address _poolToken, address[] memory _updatedMarkets)
    public
    view
    returns (bool);

Parameters

NameTypeDescription
_useraddressThe address of the user to check.
_poolTokenaddressThe address of the borrowed market to check.
_updatedMarketsaddress[]The list of markets of which to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
<none>boolwhether or not the user is liquidatable.

_getUserSupplyBalanceInOf

INTERNAL ///

Returns the supply balance of _user in the _poolToken market.

Note: Computes the result with the stored indexes, which are not always the most up to date ones.

function _getUserSupplyBalanceInOf(address _poolToken, address _user, uint256 _p2pSupplyIndex, uint256 _poolSupplyIndex)
    internal
    view
    returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the supply amount.
_useraddressThe address of the user.
_p2pSupplyIndexuint256
_poolSupplyIndexuint256

Returns

NameTypeDescription
<none>uint256The supply balance of the user (in underlying).

_getUserBorrowBalanceInOf

Returns the borrow balance of _user in the _poolToken market.

function _getUserBorrowBalanceInOf(address _poolToken, address _user, uint256 _p2pBorrowIndex, uint256 _poolBorrowIndex)
    internal
    view
    returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the borrow amount.
_useraddressThe address of the user.
_p2pBorrowIndexuint256
_poolBorrowIndexuint256

Returns

NameTypeDescription
<none>uint256The borrow balance of the user (in underlying).

_getUserHypotheticalLiquidityDataForAsset

Returns the data related to _poolToken for the _user, by optionally computing virtually updated pool and peer-to-peer indexes.

function _getUserHypotheticalLiquidityDataForAsset(
    address _user,
    address _poolToken,
    bool _getUpdatedIndexes,
    ICompoundOracle _oracle,
    uint256 _withdrawnAmount,
    uint256 _borrowedAmount
) internal view returns (Types.AssetLiquidityData memory assetData);

Parameters

NameTypeDescription
_useraddressThe user to determine data for.
_poolTokenaddressThe address of the market.
_getUpdatedIndexesboolWhether to compute virtually updated pool and peer-to-peer indexes.
_oracleICompoundOracleThe oracle used.
_withdrawnAmountuint256The amount to hypothetically withdraw from the given market (in underlying).
_borrowedAmountuint256The amount to hypothetically borrow from the given market (in underlying).

Returns

NameTypeDescription
assetDataTypes.AssetLiquidityDataThe data related to this asset.

_isLiquidatable

Returns whether a liquidation can be performed on the given user. This function checks for the user's health factor as well as whether the user is borrowing from the given deprecated market.

function _isLiquidatable(address _user, address _poolTokenDeprecated, address[] memory _updatedMarkets)
    internal
    view
    returns (bool);

Parameters

NameTypeDescription
_useraddressThe address of the user to check.
_poolTokenDeprecatedaddressThe address of the deprecated borrowed market to check.
_updatedMarketsaddress[]The list of markets of which to compute virtually updated pool and peer-to-peer indexes.

Returns

NameTypeDescription
<none>boolwhether or not the user is liquidatable.

Errors

CompoundOracleFailed

ERRORS ///

Thrown when the Compound's oracle failed.

error CompoundOracleFailed();

Contents

InterestRatesModel

Git Source

Functions

computeGrowthFactors

Computes and returns the new supply/borrow growth factors associated to the given market's pool & peer-to-peer indexes.

function computeGrowthFactors(
    uint256 _newPoolSupplyIndex,
    uint256 _newPoolBorrowIndex,
    Types.LastPoolIndexes memory _lastPoolIndexes,
    uint256 _p2pIndexCursor,
    uint256 _reserveFactor
) internal pure returns (GrowthFactors memory growthFactors);

Parameters

NameTypeDescription
_newPoolSupplyIndexuint256The current pool supply index.
_newPoolBorrowIndexuint256The current pool borrow index.
_lastPoolIndexesTypes.LastPoolIndexesThe last stored pool indexes.
_p2pIndexCursoruint256The peer-to-peer index cursor for the given market.
_reserveFactoruint256The reserve factor of the given market.

Returns

NameTypeDescription
growthFactorsGrowthFactorsThe market's indexes growth factors (in wad).

computeP2PIndex

Computes and returns the new peer-to-peer supply/borrow index of a market given its parameters.

function computeP2PIndex(P2PIndexComputeParams memory _params) internal pure returns (uint256 newP2PIndex);

Parameters

NameTypeDescription
_paramsP2PIndexComputeParamsThe computation parameters.

Returns

NameTypeDescription
newP2PIndexuint256The updated peer-to-peer index (in wad).

computeP2PSupplyRatePerBlock

Computes and returns the peer-to-peer supply rate per block of a market given its parameters.

function computeP2PSupplyRatePerBlock(P2PRateComputeParams memory _params)
    internal
    pure
    returns (uint256 p2pSupplyRate);

Parameters

NameTypeDescription
_paramsP2PRateComputeParamsThe computation parameters.

Returns

NameTypeDescription
p2pSupplyRateuint256The peer-to-peer supply rate per block (in wad).

computeP2PBorrowRatePerBlock

Computes and returns the peer-to-peer borrow rate per block of a market given its parameters.

function computeP2PBorrowRatePerBlock(P2PRateComputeParams memory _params)
    internal
    pure
    returns (uint256 p2pBorrowRate);

Parameters

NameTypeDescription
_paramsP2PRateComputeParamsThe computation parameters.

Returns

NameTypeDescription
p2pBorrowRateuint256The peer-to-peer borrow rate per block (in wad).

Structs

GrowthFactors

STRUCTS ///

struct GrowthFactors {
    uint256 poolSupplyGrowthFactor;
    uint256 poolBorrowGrowthFactor;
    uint256 p2pSupplyGrowthFactor;
    uint256 p2pBorrowGrowthFactor;
}

P2PIndexComputeParams

struct P2PIndexComputeParams {
    uint256 poolGrowthFactor;
    uint256 p2pGrowthFactor;
    uint256 lastPoolIndex;
    uint256 lastP2PIndex;
    uint256 p2pDelta;
    uint256 p2pAmount;
}

P2PRateComputeParams

struct P2PRateComputeParams {
    uint256 poolRate;
    uint256 p2pRate;
    uint256 poolIndex;
    uint256 p2pIndex;
    uint256 p2pDelta;
    uint256 p2pAmount;
    uint16 reserveFactor;
}

Types

Git Source

Author: Morpho Labs.

Common types and structs used in Morpho contracts.

Structs

SupplyBalance

STRUCTS ///

struct SupplyBalance {
    uint256 inP2P;
    uint256 onPool;
}

BorrowBalance

struct BorrowBalance {
    uint256 inP2P;
    uint256 onPool;
}

Indexes

struct Indexes {
    uint256 p2pSupplyIndex;
    uint256 p2pBorrowIndex;
    uint256 poolSupplyIndex;
    uint256 poolBorrowIndex;
}

MaxGasForMatching

struct MaxGasForMatching {
    uint64 supply;
    uint64 borrow;
    uint64 withdraw;
    uint64 repay;
}

Delta

struct Delta {
    uint256 p2pSupplyDelta;
    uint256 p2pBorrowDelta;
    uint256 p2pSupplyAmount;
    uint256 p2pBorrowAmount;
}

AssetLiquidityData

struct AssetLiquidityData {
    uint256 collateralUsd;
    uint256 maxDebtUsd;
    uint256 debtUsd;
    uint256 underlyingPrice;
    uint256 collateralFactor;
}

LiquidityData

struct LiquidityData {
    uint256 collateralUsd;
    uint256 maxDebtUsd;
    uint256 debtUsd;
}

LastPoolIndexes

struct LastPoolIndexes {
    uint32 lastUpdateBlockNumber;
    uint112 lastSupplyPoolIndex;
    uint112 lastBorrowPoolIndex;
}

MarketParameters

struct MarketParameters {
    uint16 reserveFactor;
    uint16 p2pIndexCursor;
}

MarketStatus

struct MarketStatus {
    bool isCreated;
    bool isPaused;
    bool isPartiallyPaused;
}

MarketPauseStatus

struct MarketPauseStatus {
    bool isSupplyPaused;
    bool isBorrowPaused;
    bool isWithdrawPaused;
    bool isRepayPaused;
    bool isLiquidateCollateralPaused;
    bool isLiquidateBorrowPaused;
    bool isDeprecated;
}

Enums

PositionType

ENUMS ///

enum PositionType {
    SUPPLIERS_IN_P2P,
    SUPPLIERS_ON_POOL,
    BORROWERS_IN_P2P,
    BORROWERS_ON_POOL
}

InterestRatesManager

Git Source

Inherits: IInterestRatesManager, MorphoStorage

Author: Morpho Labs.

Smart contract handling the computation of indexes used for peer-to-peer interactions.

This contract inherits from MorphoStorage so that Morpho can delegate calls to this contract.

Functions

updateP2PIndexes

EXTERNAL ///

Updates the peer-to-peer indexes.

function updateP2PIndexes(address _poolToken) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.

_computeP2PIndexes

INTERNAL ///

Computes and returns new peer-to-peer indexes.

function _computeP2PIndexes(Params memory _params)
    internal
    pure
    returns (uint256 newP2PSupplyIndex, uint256 newP2PBorrowIndex);

Parameters

NameTypeDescription
_paramsParamsComputation parameters.

Returns

NameTypeDescription
newP2PSupplyIndexuint256The updated p2pSupplyIndex.
newP2PBorrowIndexuint256The updated p2pBorrowIndex.

Events

P2PIndexesUpdated

EVENTS ///

Emitted when the peer-to-peer indexes of a market are updated.

event P2PIndexesUpdated(
    address indexed _poolToken,
    uint256 _p2pSupplyIndex,
    uint256 _p2pBorrowIndex,
    uint256 _poolSupplyIndex,
    uint256 _poolBorrowIndex
);

Structs

Params

STRUCTS ///

struct Params {
    uint256 lastP2PSupplyIndex;
    uint256 lastP2PBorrowIndex;
    uint256 poolSupplyIndex;
    uint256 poolBorrowIndex;
    Types.LastPoolIndexes lastPoolIndexes;
    uint256 reserveFactor;
    uint256 p2pIndexCursor;
    Types.Delta delta;
}

MatchingEngine

Git Source

Inherits: MorphoUtils

Author: Morpho Labs.

Smart contract managing the matching engine.

Functions

_matchSuppliers

INTERNAL ///

Matches suppliers' liquidity waiting on Compound up to the given _amount and moves it to peer-to-peer.

Note: This function expects Compound's exchange rate and peer-to-peer indexes to have been updated.

function _matchSuppliers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256 matched, uint256 gasConsumedInMatching);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to match suppliers.
_amountuint256The token amount to search for (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
matcheduint256The amount of liquidity matched (in underlying).
gasConsumedInMatchinguint256The amount of gas consumed within the matching loop.

_unmatchSuppliers

Unmatches suppliers' liquidity in peer-to-peer up to the given _amount and moves it to Compound.

Note: This function expects Compound's exchange rate and peer-to-peer indexes to have been updated.

function _unmatchSuppliers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to unmatch suppliers.
_amountuint256The amount to search for (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
<none>uint256The amount unmatched (in underlying).

_matchBorrowers

Matches borrowers' liquidity waiting on Compound up to the given _amount and moves it to peer-to-peer.

Note: This function expects stored indexes to have been updated

function _matchBorrowers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256 matched, uint256 gasConsumedInMatching);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to match borrowers.
_amountuint256The amount to search for (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
matcheduint256The amount of liquidity matched (in underlying).
gasConsumedInMatchinguint256The amount of gas consumed within the matching loop.

_unmatchBorrowers

Unmatches borrowers' liquidity in peer-to-peer for the given _amount and moves it to Compound.

Note: This function expects and peer-to-peer indexes to have been updated.

function _unmatchBorrowers(address _poolToken, uint256 _amount, uint256 _maxGasForMatching)
    internal
    returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to unmatch borrowers.
_amountuint256The amount to unmatch (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

Returns

NameTypeDescription
<none>uint256The amount unmatched (in underlying).

_updateSupplierInDS

Updates the given _user's position in the supplier data structures.

function _updateSupplierInDS(address _poolToken, address _user) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to update the suppliers data structure.
_useraddressThe address of the user.

_updateBorrowerInDS

Updates the given _user's position in the borrower data structures.

function _updateBorrowerInDS(address _poolToken, address _user) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to update the borrowers data structure.
_useraddressThe address of the user.

Events

SupplierPositionUpdated

Emitted when the position of a supplier is updated.

event SupplierPositionUpdated(
    address indexed _user, address indexed _poolToken, uint256 _balanceOnPool, uint256 _balanceInP2P
);

BorrowerPositionUpdated

Emitted when the position of a borrower is updated.

event BorrowerPositionUpdated(
    address indexed _user, address indexed _poolToken, uint256 _balanceOnPool, uint256 _balanceInP2P
);

Structs

UnmatchVars

STRUCTS ///

struct UnmatchVars {
    uint256 p2pIndex;
    uint256 toUnmatch;
    uint256 poolIndex;
    uint256 inUnderlying;
    uint256 gasLeftAtTheBeginning;
}

MatchVars

struct MatchVars {
    uint256 p2pIndex;
    uint256 toMatch;
    uint256 poolIndex;
    uint256 inUnderlying;
    uint256 gasLeftAtTheBeginning;
}

Morpho

Git Source

Inherits: MorphoGovernance

Author: Morpho Labs.

Main Morpho contract handling user interactions and pool interactions.

Functions

supply

EXTERNAL ///

Supplies underlying tokens to a specific market.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function supply(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying) to supply.

supply

Supplies underlying tokens to a specific market, on behalf of a given user.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function supply(address _poolToken, address _onBehalf, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying) to supply.

supply

Supplies underlying tokens to a specific market, on behalf of a given user, specifying a gas threshold at which to cut the matching engine.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching)
    external
    nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying) to supply.
_maxGasForMatchinguint256The gas threshold at which to stop the matching engine.

borrow

Borrows underlying tokens from a specific market.

function borrow(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).

borrow

Borrows underlying tokens from a specific market, specifying a gas threshold at which to stop the matching engine.

function borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The gas threshold at which to stop the matching engine.

withdraw

Withdraws underlying tokens from a specific market.

function withdraw(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of tokens (in underlying) to withdraw from supply.

withdraw

Withdraws underlying tokens from a specific market.

function withdraw(address _poolToken, uint256 _amount, address _receiver) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of tokens (in underlying) to withdraw from supply.
_receiveraddressThe address to send withdrawn tokens to.

repay

Repays the debt of the sender, up to the amount provided.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function repay(address _poolToken, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying) to repay from borrow.

repay

Repays debt of a given user, up to the amount provided.

msg.sender must have approved Morpho's contract to spend the underlying _amount.

function repay(address _poolToken, address _onBehalf, uint256 _amount) external nonReentrant;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying) to repay from borrow.

liquidate

Liquidates a position.

function liquidate(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external
    nonReentrant;

Parameters

NameTypeDescription
_poolTokenBorrowedaddressThe address of the pool token the liquidator wants to repay.
_poolTokenCollateraladdressThe address of the collateral pool token the liquidator wants to seize.
_borroweraddressThe address of the borrower to liquidate.
_amountuint256The amount of token (in underlying) to repay.

claimRewards

Claims rewards for the given assets.

The incentives vault will never be implemented. Thus the second parameter of this function becomes useless.

function claimRewards(address[] calldata _cTokenAddresses, bool)
    external
    nonReentrant
    returns (uint256 amountOfRewards);

Parameters

NameTypeDescription
_cTokenAddressesaddress[]The cToken addresses to claim rewards from.
<none>bool

Returns

NameTypeDescription
amountOfRewardsuint256The amount of rewards claimed (in COMP).

receive

Allows to receive ETH.

receive() external payable;

_supply

INTERNAL ///

function _supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) internal;

_borrow

function _borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) internal;

_withdraw

function _withdraw(address _poolToken, uint256 _amount, address _receiver, uint256 _maxGasForMatching) internal;

_repay

function _repay(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) internal;

Events

RewardsClaimed

EVENTS ///

Emitted when a user claims rewards.

event RewardsClaimed(address indexed _user, uint256 _amountClaimed, bool indexed _traded);

Errors

ClaimRewardsPaused

ERRORS ///

Thrown when claiming rewards is paused.

error ClaimRewardsPaused();

MorphoGovernance

Git Source

Inherits: MorphoUtils

Author: Morpho Labs.

Governance functions for Morpho.

Functions

initialize

UPGRADE ///

Initializes the Morpho contract.

function initialize(
    IPositionsManager _positionsManager,
    IInterestRatesManager _interestRatesManager,
    IComptroller _comptroller,
    Types.MaxGasForMatching memory _defaultMaxGasForMatching,
    uint256 _dustThreshold,
    uint256 _maxSortedUsers,
    address _cEth,
    address _wEth
) external initializer;

Parameters

NameTypeDescription
_positionsManagerIPositionsManagerThe positionsManager.
_interestRatesManagerIInterestRatesManagerThe interestRatesManager.
_comptrollerIComptrollerThe comptroller.
_defaultMaxGasForMatchingTypes.MaxGasForMatchingThe defaultMaxGasForMatching.
_dustThresholduint256The dustThreshold.
_maxSortedUsersuint256The _maxSortedUsers.
_cEthaddressThe cETH address.
_wEthaddressThe wETH address.

setMaxSortedUsers

GOVERNANCE ///

Sets maxSortedUsers.

function setMaxSortedUsers(uint256 _newMaxSortedUsers) external onlyOwner;

Parameters

NameTypeDescription
_newMaxSortedUsersuint256The new maxSortedUsers value.

setDefaultMaxGasForMatching

Sets defaultMaxGasForMatching.

function setDefaultMaxGasForMatching(Types.MaxGasForMatching memory _defaultMaxGasForMatching) external onlyOwner;

Parameters

NameTypeDescription
_defaultMaxGasForMatchingTypes.MaxGasForMatchingThe new defaultMaxGasForMatching.

setPositionsManager

Sets the positionsManager.

function setPositionsManager(IPositionsManager _positionsManager) external onlyOwner;

Parameters

NameTypeDescription
_positionsManagerIPositionsManagerThe new positionsManager.

setInterestRatesManager

Sets the interestRatesManager.

function setInterestRatesManager(IInterestRatesManager _interestRatesManager) external onlyOwner;

Parameters

NameTypeDescription
_interestRatesManagerIInterestRatesManagerThe new interestRatesManager contract.

setRewardsManager

Sets the rewardsManager.

function setRewardsManager(IRewardsManager _rewardsManager) external onlyOwner;

Parameters

NameTypeDescription
_rewardsManagerIRewardsManagerThe new rewardsManager.

setTreasuryVault

Sets the treasuryVault.

function setTreasuryVault(address _treasuryVault) external onlyOwner;

Parameters

NameTypeDescription
_treasuryVaultaddressThe address of the new treasuryVault.

setDustThreshold

Sets dustThreshold.

function setDustThreshold(uint256 _dustThreshold) external onlyOwner;

Parameters

NameTypeDescription
_dustThresholduint256The new dustThreshold.

setReserveFactor

Sets the reserveFactor.

function setReserveFactor(address _poolToken, uint16 _newReserveFactor)
    external
    onlyOwner
    isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe market on which to set the _newReserveFactor.
_newReserveFactoruint16The proportion of the interest earned by users sent to the DAO, in basis point.

setP2PIndexCursor

Sets a new peer-to-peer cursor.

function setP2PIndexCursor(address _poolToken, uint16 _p2pIndexCursor) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_p2pIndexCursoruint16The new peer-to-peer cursor.

setIsSupplyPaused

Sets isSupplyPaused for a given market.

function setIsSupplyPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsBorrowPaused

Sets isBorrowPaused for a given market.

function setIsBorrowPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsWithdrawPaused

Sets isWithdrawPaused for a given market.

function setIsWithdrawPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsRepayPaused

Sets isRepayPaused for a given market.

function setIsRepayPaused(address _poolToken, bool _isPaused) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsLiquidateCollateralPaused

Sets isLiquidateCollateralPaused for a given market.

function setIsLiquidateCollateralPaused(address _poolToken, bool _isPaused)
    external
    onlyOwner
    isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsLiquidateBorrowPaused

Sets isLiquidateBorrowPaused for a given market.

function setIsLiquidateBorrowPaused(address _poolToken, bool _isPaused)
    external
    onlyOwner
    isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

setIsPausedForAllMarkets

Sets the pause status for all markets.

function setIsPausedForAllMarkets(bool _isPaused) external onlyOwner;

Parameters

NameTypeDescription
_isPausedboolThe new pause status, true to pause the mechanism.

setIsP2PDisabled

Sets isP2PDisabled for a given market.

function setIsP2PDisabled(address _poolToken, bool _isP2PDisabled) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market of which to enable/disable peer-to-peer matching.
_isP2PDisabledboolTrue to disable the peer-to-peer market.

setIsClaimRewardsPaused

Sets isClaimRewardsPaused.

function setIsClaimRewardsPaused(bool _isPaused) external onlyOwner;

Parameters

NameTypeDescription
_isPausedboolThe new pause status, true to pause the mechanism.

setIsDeprecated

Sets a market as deprecated (allows liquidation of every position on this market).

function setIsDeprecated(address _poolToken, bool _isDeprecated) external onlyOwner isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isDeprecatedboolThe new deprecated status, true to deprecate the market.

increaseP2PDeltas

Increases peer-to-peer deltas, to put some liquidity back on the pool.

The current Morpho supply on the pool might not be enough to borrow _amount before resuppling it. In this case, consider calling multiple times this function.

function increaseP2PDeltas(address _poolToken, uint256 _amount) external onlyOwner;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to increase deltas.
_amountuint256The maximum amount to add to the deltas (in underlying).

claimToTreasury

Transfers the protocol reserve fee to the DAO.

function claimToTreasury(address[] calldata _poolTokens, uint256[] calldata _amounts) external onlyOwner;

Parameters

NameTypeDescription
_poolTokensaddress[]The addresses of the pool token addresses on which to claim the reserve fee.
_amountsuint256[]The list of amounts of underlying tokens to claim on each market.

createMarket

Creates a new market to borrow/supply in.

function createMarket(address _poolToken, Types.MarketParameters calldata _marketParams) external onlyOwner;

Parameters

NameTypeDescription
_poolTokenaddressThe pool token address of the given market.
_marketParamsTypes.MarketParametersThe market's parameters to set.

_setPauseStatus

INTERNAL ///

Sets all pause statuses for a given market.

function _setPauseStatus(address _poolToken, bool _isPaused) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.
_isPausedboolThe new pause status, true to pause the mechanism.

Events

DefaultMaxGasForMatchingSet

EVENTS ///

Emitted when a new defaultMaxGasForMatching is set.

event DefaultMaxGasForMatchingSet(Types.MaxGasForMatching _defaultMaxGasForMatching);

MaxSortedUsersSet

Emitted when a new value for maxSortedUsers is set.

event MaxSortedUsersSet(uint256 _newValue);

TreasuryVaultSet

Emitted when the address of the treasuryVault is set.

event TreasuryVaultSet(address indexed _newTreasuryVaultAddress);

PositionsManagerSet

Emitted when the positionsManager is set.

event PositionsManagerSet(address indexed _positionsManager);

RewardsManagerSet

Emitted when the rewardsManager is set.

event RewardsManagerSet(address indexed _newRewardsManagerAddress);

InterestRatesSet

Emitted when the interestRatesManager is set.

event InterestRatesSet(address indexed _interestRatesManager);

DustThresholdSet

Emitted when a new dustThreshold is set.

event DustThresholdSet(uint256 _dustThreshold);

ReserveFactorSet

Emitted when the reserveFactor is set.

event ReserveFactorSet(address indexed _poolToken, uint16 _newValue);

P2PIndexCursorSet

Emitted when the p2pIndexCursor is set.

event P2PIndexCursorSet(address indexed _poolToken, uint16 _newValue);

ReserveFeeClaimed

Emitted when a reserve fee is claimed.

event ReserveFeeClaimed(address indexed _poolToken, uint256 _amountClaimed);

P2PStatusSet

Emitted when the value of isP2PDisabled is set.

event P2PStatusSet(address indexed _poolToken, bool _isP2PDisabled);

IsSupplyPausedSet

Emitted when supplying is paused or unpaused.

event IsSupplyPausedSet(address indexed _poolToken, bool _isPaused);

IsBorrowPausedSet

Emitted when borrowing is paused or unpaused.

event IsBorrowPausedSet(address indexed _poolToken, bool _isPaused);

IsWithdrawPausedSet

Emitted when withdrawing is paused or unpaused.

event IsWithdrawPausedSet(address indexed _poolToken, bool _isPaused);

IsRepayPausedSet

Emitted when repaying is paused or unpaused.

event IsRepayPausedSet(address indexed _poolToken, bool _isPaused);

IsLiquidateCollateralPausedSet

Emitted when liquidating on this market as collateral is paused or unpaused.

event IsLiquidateCollateralPausedSet(address indexed _poolToken, bool _isPaused);

IsLiquidateBorrowPausedSet

Emitted when liquidating on this market as borrow is paused or unpaused.

event IsLiquidateBorrowPausedSet(address indexed _poolToken, bool _isPaused);

IsDeprecatedSet

Emitted when a market is set as deprecated or not.

event IsDeprecatedSet(address indexed _poolToken, bool _isDeprecated);

ClaimRewardsPauseStatusSet

Emitted when claiming rewards is paused or unpaused.

event ClaimRewardsPauseStatusSet(bool _isPaused);

MarketCreated

Emitted when a new market is created.

event MarketCreated(address indexed _poolToken, uint16 _reserveFactor, uint16 _p2pIndexCursor);

Errors

MarketCreationFailedOnCompound

ERRORS ///

Thrown when the creation of a market failed on Compound and kicks back Compound error code.

error MarketCreationFailedOnCompound(uint256 errorCode);

ExceedsMaxBasisPoints

Thrown when the input is above the max basis points value (100%).

error ExceedsMaxBasisPoints();

MarketAlreadyCreated

Thrown when the market is already created.

error MarketAlreadyCreated();

AmountIsZero

Thrown when the amount is equal to 0.

error AmountIsZero();

ZeroAddress

Thrown when the address is the zero address.

error ZeroAddress();

BorrowNotPaused

Thrown when market borrow is not paused.

error BorrowNotPaused();

MarketIsDeprecated

Thrown when market is deprecated.

error MarketIsDeprecated();

MorphoStorage

Git Source

Inherits: OwnableUpgradeable, ReentrancyGuardUpgradeable

Author: Morpho Labs.

All storage variables used in Morpho contracts.

State Variables

CTOKEN_DECIMALS

GLOBAL STORAGE ///

uint8 public constant CTOKEN_DECIMALS = 8;

MAX_BASIS_POINTS

uint16 public constant MAX_BASIS_POINTS = 100_00;

WAD

uint256 public constant WAD = 1e18;

maxSortedUsers

uint256 public maxSortedUsers;

dustThreshold

uint256 public dustThreshold;

defaultMaxGasForMatching

Types.MaxGasForMatching public defaultMaxGasForMatching;

suppliersInP2P

POSITIONS STORAGE ///

mapping(address => DoubleLinkedList.List) internal suppliersInP2P;

suppliersOnPool

mapping(address => DoubleLinkedList.List) internal suppliersOnPool;

borrowersInP2P

mapping(address => DoubleLinkedList.List) internal borrowersInP2P;

borrowersOnPool

mapping(address => DoubleLinkedList.List) internal borrowersOnPool;

supplyBalanceInOf

mapping(address => mapping(address => Types.SupplyBalance)) public supplyBalanceInOf;

borrowBalanceInOf

mapping(address => mapping(address => Types.BorrowBalance)) public borrowBalanceInOf;

userMembership

mapping(address => mapping(address => bool)) public userMembership;

enteredMarkets

mapping(address => address[]) public enteredMarkets;

marketsCreated

MARKETS STORAGE ///

address[] internal marketsCreated;

p2pDisabled

mapping(address => bool) public p2pDisabled;

p2pSupplyIndex

mapping(address => uint256) public p2pSupplyIndex;

p2pBorrowIndex

mapping(address => uint256) public p2pBorrowIndex;

lastPoolIndexes

mapping(address => Types.LastPoolIndexes) public lastPoolIndexes;

marketParameters

mapping(address => Types.MarketParameters) public marketParameters;

marketStatus

mapping(address => Types.MarketStatus) public marketStatus;

deltas

mapping(address => Types.Delta) public deltas;

positionsManager

CONTRACTS AND ADDRESSES ///

IPositionsManager public positionsManager;

incentivesVault

address public incentivesVault;

rewardsManager

IRewardsManager public rewardsManager;

interestRatesManager

IInterestRatesManager public interestRatesManager;

comptroller

IComptroller public comptroller;

treasuryVault

address public treasuryVault;

cEth

address public cEth;

wEth

address public wEth;

lastBorrowBlock

APPENDIX STORAGE ///

mapping(address => uint256) public lastBorrowBlock;

isClaimRewardsPaused

bool public isClaimRewardsPaused;

marketPauseStatus

mapping(address => Types.MarketPauseStatus) public marketPauseStatus;

Functions

constructor

CONSTRUCTOR ///

Constructs the contract.

The contract is automatically marked as initialized when deployed so that nobody can highjack the implementation contract.

constructor() initializer;

MorphoUtils

Git Source

Inherits: MorphoStorage

Author: Morpho Labs.

Modifiers, getters and other util functions for Morpho.

Functions

isMarketCreated

MODIFIERS ///

Prevents to update a market not created yet.

modifier isMarketCreated(address _poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.

getEnteredMarkets

EXTERNAL ///

Returns all markets entered by a given user.

function getEnteredMarkets(address _user) external view returns (address[] memory);

Parameters

NameTypeDescription
_useraddressThe address of the user.

Returns

NameTypeDescription
<none>address[]The list of markets entered by this user.

getAllMarkets

Returns all created markets.

function getAllMarkets() external view returns (address[] memory);

Returns

NameTypeDescription
<none>address[]The list of market addresses.

getHead

Gets the head of the data structure on a specific market (for UI).

function getHead(address _poolToken, Types.PositionType _positionType) external view returns (address head);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to get the head.
_positionTypeTypes.PositionTypeThe type of user from which to get the head.

Returns

NameTypeDescription
headaddressThe head in the data structure.

getNext

Gets the next user after _user in the data structure on a specific market (for UI).

Beware that this function does not give the account with the highest liquidity.

function getNext(address _poolToken, Types.PositionType _positionType, address _user)
    external
    view
    returns (address next);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market from which to get the user.
_positionTypeTypes.PositionTypeThe type of user from which to get the next user.
_useraddressThe address of the user from which to get the next user.

Returns

NameTypeDescription
nextaddressThe next user in the data structure.

updateP2PIndexes

Updates the peer-to-peer indexes.

Note: This function updates the exchange rate on Compound. As a consequence only a call to exchangeRateStored() is necessary to get the most up to date exchange rate.

function updateP2PIndexes(address _poolToken) external isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.

_updateP2PIndexes

INTERNAL ///

Updates the peer-to-peer indexes.

Note: This function updates the exchange rate on Compound. As a consequence only a call to exchangeRateStored() is necessary to get the most up to date exchange rate.

function _updateP2PIndexes(address _poolToken) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to update.

_isLiquidatable

Checks whether the user has enough collateral to maintain such a borrow position.

Expects the given user's entered markets to include the given market.

Expects the given market's pool & peer-to-peer indexes to have been updated.

Expects _withdrawnAmount to be less than or equal to the given user's supply on the given market.

function _isLiquidatable(address _user, address _poolToken, uint256 _withdrawnAmount, uint256 _borrowedAmount)
    internal
    view
    returns (bool);

Parameters

NameTypeDescription
_useraddressThe user to check.
_poolTokenaddressThe market to hypothetically withdraw/borrow in.
_withdrawnAmountuint256The amount of tokens to hypothetically withdraw (in underlying).
_borrowedAmountuint256The amount of tokens to hypothetically borrow (in underlying).

_getUserLiquidityDataForAsset

Returns the data related to _poolToken for the _user.

Note: Must be called after calling _updateP2PIndexes() to have the most up-to-date indexes.

function _getUserLiquidityDataForAsset(address _user, address _poolToken, ICompoundOracle _oracle)
    internal
    view
    returns (Types.AssetLiquidityData memory assetData);

Parameters

NameTypeDescription
_useraddressThe user to determine data for.
_poolTokenaddressThe address of the market.
_oracleICompoundOracleThe oracle used.

Returns

NameTypeDescription
assetDataTypes.AssetLiquidityDataThe data related to this asset.

_getUserSupplyBalanceInOf

Returns the supply balance of _user in the _poolToken market.

Note: Computes the result with the stored indexes, which are not always the most up to date ones.

function _getUserSupplyBalanceInOf(address _poolToken, address _user) internal view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the supply amount.
_useraddressThe address of the user.

Returns

NameTypeDescription
<none>uint256The supply balance of the user (in underlying).

_getUserBorrowBalanceInOf

Returns the borrow balance of _user in the _poolToken market.

Note: Computes the result with the stored indexes, which are not always the most up to date ones.

function _getUserBorrowBalanceInOf(address _poolToken, address _user) internal view returns (uint256);

Parameters

NameTypeDescription
_poolTokenaddressThe market where to get the borrow amount.
_useraddressThe address of the user.

Returns

NameTypeDescription
<none>uint256The borrow balance of the user (in underlying).

_getUnderlying

Returns the underlying ERC20 token related to the pool token.

function _getUnderlying(address _poolToken) internal view returns (ERC20);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token.

Returns

NameTypeDescription
<none>ERC20The underlying ERC20 token.

Errors

CompoundOracleFailed

ERRORS ///

Thrown when the Compound's oracle failed.

error CompoundOracleFailed();

MarketNotCreated

Thrown when the market is not created yet.

error MarketNotCreated();

PositionsManager

Git Source

Inherits: IPositionsManager, MatchingEngine

Author: Morpho Labs.

Main Logic of Morpho Protocol, implementation of the 5 main functionalities: supply, borrow, withdraw, repay and liquidate.

Functions

supplyLogic

LOGIC ///

Implements supply logic.

function supplyLogic(address _poolToken, address _from, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching)
    external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token the user wants to interact with.
_fromaddressThe address of the account sending funds.
_onBehalfaddressThe address of the account whose positions will be updated.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

borrowLogic

Peer-to-peer supply /// Pool supply ///

Implements borrow logic.

function borrowLogic(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

withdrawLogic

Peer-to-peer borrow /// Pool borrow ///

Implements withdraw logic with security checks.

function withdrawLogic(
    address _poolToken,
    uint256 _amount,
    address _supplier,
    address _receiver,
    uint256 _maxGasForMatching
) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_supplieraddressThe address of the supplier.
_receiveraddressThe address of the user who will receive the tokens.
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

repayLogic

Implements repay logic with security checks.

function repayLogic(
    address _poolToken,
    address _repayer,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) external;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_repayeraddressThe address of the account repaying the debt.
_onBehalfaddressThe address of the account whose debt is repaid.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

liquidateLogic

Liquidates a position.

function liquidateLogic(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount)
    external;

Parameters

NameTypeDescription
_poolTokenBorrowedaddressThe address of the pool token the liquidator wants to repay.
_poolTokenCollateraladdressThe address of the collateral pool token the liquidator wants to seize.
_borroweraddressThe address of the borrower to liquidate.
_amountuint256The amount of token (in underlying) to repay.

increaseP2PDeltasLogic

Implements increaseP2PDeltas logic.

The current Morpho supply on the pool might not be enough to borrow _amount before resupplying it. In this case, consider calling this function multiple times.

function increaseP2PDeltasLogic(address _poolToken, uint256 _amount) external isMarketCreated(_poolToken);

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market on which to increase deltas.
_amountuint256The maximum amount to add to the deltas (in underlying).

_unsafeWithdrawLogic

INTERNAL ///

Implements withdraw logic without security checks.

function _unsafeWithdrawLogic(
    address _poolToken,
    uint256 _amount,
    address _supplier,
    address _receiver,
    uint256 _maxGasForMatching
) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_amountuint256The amount of token (in underlying).
_supplieraddressThe address of the supplier.
_receiveraddressThe address of the user who will receive the tokens.
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

_unsafeRepayLogic

Pool withdraw /// Transfer withdraw /// Breaking withdraw ///

Implements repay logic without security checks.

function _unsafeRepayLogic(
    address _poolToken,
    address _repayer,
    address _onBehalf,
    uint256 _amount,
    uint256 _maxGasForMatching
) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market the user wants to interact with.
_repayeraddressThe address of the account repaying the debt.
_onBehalfaddressThe address of the account whose debt is repaid.
_amountuint256The amount of token (in underlying).
_maxGasForMatchinguint256The maximum amount of gas to consume within a matching engine loop.

_supplyToPool

Pool repay /// Transfer repay /// Breaking repay ///

Supplies underlying tokens to Compound.

function _supplyToPool(address _poolToken, ERC20 _underlyingToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token.
_underlyingTokenERC20The underlying token of the market to supply to.
_amountuint256The amount of token (in underlying).

_withdrawFromPool

Withdraws underlying tokens from Compound.

function _withdrawFromPool(address _poolToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token.
_amountuint256The amount of token (in underlying).

_borrowFromPool

Borrows underlying tokens from Compound.

function _borrowFromPool(address _poolToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token.
_amountuint256The amount of token (in underlying).

_repayToPool

Repays underlying tokens to Compound.

function _repayToPool(address _poolToken, ERC20 _underlyingToken, uint256 _amount) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the pool token.
_underlyingTokenERC20The underlying token of the market to repay to.
_amountuint256The amount of token (in underlying).

_enterMarketIfNeeded

Enters the user into the market if not already there.

function _enterMarketIfNeeded(address _poolToken, address _user) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.
_useraddressThe address of the user to update.

_leaveMarketIfNeeded

Removes the user from the market if its balances are null.

function _leaveMarketIfNeeded(address _poolToken, address _user) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe address of the market to check.
_useraddressThe address of the user to update.

_liquidationAllowed

Returns whether a given user is liquidatable and the applicable close factor, given the deprecated status of the borrowed market.

function _liquidationAllowed(address _user, bool _isDeprecated)
    internal
    view
    returns (bool liquidationAllowed, uint256 closeFactor);

Parameters

NameTypeDescription
_useraddressThe user to check.
_isDeprecatedboolWhether the borrowed market is deprecated or not.

Returns

NameTypeDescription
liquidationAllowedboolWhether the liquidation is allowed or not.
closeFactoruint256The close factor to apply.

Events

Supplied

EVENTS ///

Emitted when a supply happens.

event Supplied(
    address indexed _supplier,
    address indexed _onBehalf,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Borrowed

Emitted when a borrow happens.

event Borrowed(
    address indexed _borrower,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Withdrawn

Emitted when a withdrawal happens.

event Withdrawn(
    address indexed _supplier,
    address indexed _receiver,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Repaid

Emitted when a repayment happens.

event Repaid(
    address indexed _repayer,
    address indexed _onBehalf,
    address indexed _poolToken,
    uint256 _amount,
    uint256 _balanceOnPool,
    uint256 _balanceInP2P
);

Liquidated

Emitted when a liquidation happens.

event Liquidated(
    address _liquidator,
    address indexed _liquidated,
    address indexed _poolTokenBorrowed,
    uint256 _amountRepaid,
    address indexed _poolTokenCollateral,
    uint256 _amountSeized
);

P2PDeltasIncreased

Emitted when the peer-to-peer deltas are increased by the governance.

event P2PDeltasIncreased(address indexed _poolToken, uint256 _amount);

P2PBorrowDeltaUpdated

Emitted when the borrow peer-to-peer delta is updated.

event P2PBorrowDeltaUpdated(address indexed _poolToken, uint256 _p2pBorrowDelta);

P2PSupplyDeltaUpdated

Emitted when the supply peer-to-peer delta is updated.

event P2PSupplyDeltaUpdated(address indexed _poolToken, uint256 _p2pSupplyDelta);

P2PAmountsUpdated

Emitted when the supply and borrow peer-to-peer amounts are updated.

event P2PAmountsUpdated(address indexed _poolToken, uint256 _p2pSupplyAmount, uint256 _p2pBorrowAmount);

Errors

AmountAboveWhatAllowedToRepay

ERRORS ///

Thrown when the amount repaid during the liquidation is above what is allowed to be repaid.

error AmountAboveWhatAllowedToRepay();

BorrowOnCompoundFailed

Thrown when the borrow on Compound failed and throws back the Compound error code.

error BorrowOnCompoundFailed(uint256 errorCode);

RedeemOnCompoundFailed

Thrown when the redeem on Compound failed and throws back the Compound error code.

error RedeemOnCompoundFailed(uint256 errorCode);

RepayOnCompoundFailed

Thrown when the repay on Compound failed and throws back the Compound error code.

error RepayOnCompoundFailed(uint256 errorCode);

MintOnCompoundFailed

Thrown when the mint on Compound failed and throws back the Compound error code.

error MintOnCompoundFailed(uint256 errorCode);

UserNotMemberOfMarket

Thrown when user is not a member of the market.

error UserNotMemberOfMarket();

UnauthorisedWithdraw

Thrown when the user does not have enough remaining collateral to withdraw.

error UnauthorisedWithdraw();

UnauthorisedLiquidate

Thrown when the positions of the user is not liquidatable.

error UnauthorisedLiquidate();

UnauthorisedBorrow

Thrown when the user does not have enough collateral for the borrow.

error UnauthorisedBorrow();

WithdrawTooSmall

Thrown when the amount desired for a withdrawal is too small.

error WithdrawTooSmall();

AddressIsZero

Thrown when the address is zero.

error AddressIsZero();

AmountIsZero

Thrown when the amount is equal to 0.

error AmountIsZero();

SameBlockBorrowRepay

Thrown when a user tries to repay its debt after borrowing in the same block.

error SameBlockBorrowRepay();

SupplyIsPaused

Thrown when someone tries to supply but the supply is paused.

error SupplyIsPaused();

BorrowIsPaused

Thrown when someone tries to borrow but the borrow is paused.

error BorrowIsPaused();

WithdrawIsPaused

Thrown when someone tries to withdraw but the withdraw is paused.

error WithdrawIsPaused();

RepayIsPaused

Thrown when someone tries to repay but the repay is paused.

error RepayIsPaused();

LiquidateCollateralIsPaused

Thrown when someone tries to liquidate but the liquidation with this asset as collateral is paused.

error LiquidateCollateralIsPaused();

LiquidateBorrowIsPaused

Thrown when someone tries to liquidate but the liquidation with this asset as debt is paused.

error LiquidateBorrowIsPaused();

Structs

SupplyVars

STRUCTS ///

struct SupplyVars {
    uint256 remainingToSupply;
    uint256 poolBorrowIndex;
    uint256 toRepay;
}

WithdrawVars

struct WithdrawVars {
    uint256 remainingGasForMatching;
    uint256 remainingToWithdraw;
    uint256 poolSupplyIndex;
    uint256 p2pSupplyIndex;
    uint256 toWithdraw;
    ERC20 underlyingToken;
}

RepayVars

struct RepayVars {
    uint256 remainingGasForMatching;
    uint256 remainingToRepay;
    uint256 maxToRepayOnPool;
    uint256 poolBorrowIndex;
    uint256 p2pSupplyIndex;
    uint256 p2pBorrowIndex;
    uint256 borrowedOnPool;
    uint256 feeToRepay;
    uint256 toRepay;
}

LiquidateVars

struct LiquidateVars {
    uint256 collateralPrice;
    uint256 borrowBalance;
    uint256 supplyBalance;
    uint256 borrowedPrice;
    uint256 amountToSeize;
    uint256 closeFactor;
    bool liquidationAllowed;
}

RewardsManager

Git Source

Inherits: IRewardsManager, Initializable

Author: Morpho Labs.

This contract is used to manage the COMP rewards from the Compound protocol.

State Variables

userUnclaimedCompRewards

STORAGE ///

mapping(address => uint256) public userUnclaimedCompRewards;

compSupplierIndex

mapping(address => mapping(address => uint256)) public compSupplierIndex;

compBorrowerIndex

mapping(address => mapping(address => uint256)) public compBorrowerIndex;

localCompSupplyState

mapping(address => IComptroller.CompMarketState) public localCompSupplyState;

localCompBorrowState

mapping(address => IComptroller.CompMarketState) public localCompBorrowState;

morpho

IMorpho public morpho;

comptroller

IComptroller public comptroller;

Functions

onlyMorpho

MODIFIERS ///

Thrown when an other address than Morpho triggers the function.

modifier onlyMorpho();

constructor

CONSTRUCTOR ///

Constructs the contract.

The contract is automatically marked as initialized when deployed so that nobody can highjack the implementation contract.

constructor() initializer;

initialize

UPGRADE ///

Initializes the RewardsManager contract.

function initialize(address _morpho) external initializer;

Parameters

NameTypeDescription
_morphoaddressThe address of Morpho's main contract's proxy.

getLocalCompSupplyState

EXTERNAL ///

Returns the local COMP supply state.

function getLocalCompSupplyState(address _poolToken) external view returns (IComptroller.CompMarketState memory);

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>IComptroller.CompMarketStateThe local COMP supply state.

getLocalCompBorrowState

Returns the local COMP borrow state.

function getLocalCompBorrowState(address _poolToken) external view returns (IComptroller.CompMarketState memory);

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Returns

NameTypeDescription
<none>IComptroller.CompMarketStateThe local COMP borrow state.

claimRewards

Accrues unclaimed COMP rewards for the given cToken addresses and returns the total COMP unclaimed rewards.

This function is called by the morpho to accrue COMP rewards and reset them to 0.

The transfer of tokens is done in the morpho.

function claimRewards(address[] calldata _poolTokens, address _user)
    external
    onlyMorpho
    returns (uint256 totalUnclaimedRewards);

Parameters

NameTypeDescription
_poolTokensaddress[]The cToken addresses for which to claim rewards.
_useraddressThe address of the user.

accrueUserSupplyUnclaimedRewards

Updates the unclaimed COMP rewards of the user.

function accrueUserSupplyUnclaimedRewards(address _user, address _poolToken, uint256 _userBalance)
    external
    onlyMorpho;

Parameters

NameTypeDescription
_useraddressThe address of the user.
_poolTokenaddressThe cToken address.
_userBalanceuint256The user balance of tokens in the distribution.

accrueUserBorrowUnclaimedRewards

Updates the unclaimed COMP rewards of the user.

function accrueUserBorrowUnclaimedRewards(address _user, address _poolToken, uint256 _userBalance)
    external
    onlyMorpho;

Parameters

NameTypeDescription
_useraddressThe address of the user.
_poolTokenaddressThe cToken address.
_userBalanceuint256The user balance of tokens in the distribution.

_accrueUserUnclaimedRewards

INTERNAL ///

Accrues unclaimed COMP rewards for the cToken addresses and returns the total unclaimed COMP rewards.

function _accrueUserUnclaimedRewards(address[] calldata _poolTokens, address _user)
    internal
    returns (uint256 unclaimedRewards);

Parameters

NameTypeDescription
_poolTokensaddress[]The cToken addresses for which to accrue rewards.
_useraddressThe address of the user.

Returns

NameTypeDescription
unclaimedRewardsuint256The user unclaimed rewards.

_accrueSupplierComp

Updates supplier index and returns the accrued COMP rewards of the supplier since the last update.

function _accrueSupplierComp(address _supplier, address _poolToken, uint256 _balance) internal returns (uint256);

Parameters

NameTypeDescription
_supplieraddressThe address of the supplier.
_poolTokenaddressThe cToken address.
_balanceuint256The user balance of tokens in the distribution.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

_accrueBorrowerComp

Updates borrower index and returns the accrued COMP rewards of the borrower since the last update.

function _accrueBorrowerComp(address _borrower, address _poolToken, uint256 _balance) internal returns (uint256);

Parameters

NameTypeDescription
_borroweraddressThe address of the borrower.
_poolTokenaddressThe cToken address.
_balanceuint256The user balance of tokens in the distribution.

Returns

NameTypeDescription
<none>uint256The accrued COMP rewards.

_updateSupplyIndex

Updates the COMP supply index.

function _updateSupplyIndex(address _poolToken) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

_updateBorrowIndex

Updates the COMP borrow index.

function _updateBorrowIndex(address _poolToken) internal;

Parameters

NameTypeDescription
_poolTokenaddressThe cToken address.

Errors

OnlyMorpho

ERRORS ///

Thrown when only Morpho can call the function.

error OnlyMorpho();

InvalidCToken

Thrown when an invalid cToken address is passed to claim rewards.

error InvalidCToken();