Morpho-AaveV3 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 AaveV3 pool, you would be better off using Morpho-AaveV3.


Contracts overview

The Morpho protocol is designed at its core, with the main Morpho contract delegating calls to the PositionsManager implementation contract (to overcome the contract size limit).

The main user's entry points are exposed in the Morpho contract. It inherits from MorphoGetters, which contains all the functions used to query Morpho-AaveV3, MorphoSetters, which contains all the functions used by the governance to manage the protocol, MorphoInternal, and MorphoStorage, where the protocol's internal logic & storage is located. This contract delegates call to the PositionsManager, that has the same storage layout: this contract inherits from PositionsManagerInternal, which contains all the internal accounting logic and in turn inherits from MatchingEngine, which contains the matching engine internal functions.

It also interacts with RewardsManager, which manages AaveV3'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 also email security@morpho.org if you find something worrying.


Deployment Addresses

Morpho-Aave-V3 Optimizer (Ethereum)

Common (Ethereum)


Importing contracts

Using forge:

forge install morpho-dao/morpho-aave-v3

Development

Getting Started

  • Install Foundry.
  • Run make install to initialize the repository.
  • Create a .env file according to the .env.example file.

Testing with Foundry 🔨

Tests are run against a fork of real networks, which allows us to interact directly with the liquidity pools of AaveV3. Note that you need an RPC provider with access to Ethereum or Avalanche.

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

make install

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 the whole test suite:

make test

Or to run only tests matching an input:

make test-Borrow

Or to run only unit, internal, integration, or invariant tests:

make test-[unit/internal/integration/invariant]

For the other commands, check the Makefile.

VSCode setup

Configure your VSCode to automatically format a file on save, using forge fmt:

{
  "[solidity]": {
    "editor.formatOnSave": false
  },
  "emeraldwalk.runonsave": {
    "commands": [
      {
        "match": ".sol",
        "isAsync": true,
        "cmd": "forge fmt ${file}"
      }
    ]
  }
}

Test coverage

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

To generate the lcov report, run:

make coverage

The report is then usable either:


Storage seatbelt

foundry-storage-check is 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.


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

BulkerGateway

Git Source

Inherits: IBulkerGateway

Author: Morpho Labs.

Contract allowing to bundle multiple interactions with Morpho together.

State Variables

_WETH

The address of the WETH contract.

address internal constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

_ST_ETH

The address of the stETH contract.

address internal constant _ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;

_WST_ETH

The address of the wstETH contract.

address internal constant _WST_ETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;

_MORPHO

IMorpho internal immutable _MORPHO;

Functions

constructor

constructor(address morpho);

WETH

Returns the address of the WETH contract.

function WETH() external pure returns (address);

stETH

Returns the address of the stETH contract.

function stETH() external pure returns (address);

wstETH

Returns the address of the wstETH contract.

function wstETH() external pure returns (address);

MORPHO

Returns the address of the Morpho protocol.

function MORPHO() external view returns (address);

execute

Executes the given batch of actions, with the given input data. Those actions, if not performed in the correct order, with the proper action's configuration and with the proper inclusion of skim final calls, could leave funds in the Bulker contract.

function execute(ActionType[] calldata actions, bytes[] calldata data) external payable;

Parameters

NameTypeDescription
actionsActionType[]The batch of action to execute, one after the other.
databytes[]The array of data corresponding to each input action.

receive

Only the WETH contract is allowed to transfer ETH to this contract, without any calldata.

receive() external payable;

_performAction

Performs the given action, given its associated parameters.

function _performAction(ActionType action, bytes calldata data) internal;

Parameters

NameTypeDescription
actionActionTypeThe type of action to perform on behalf of the caller.
databytesThe data to decode, associated with the action.

_approve2

Approves the given amount of asset from sender to be spent by this contract via Permit2 with the given deadline & EIP712 signature.

function _approve2(bytes calldata data) internal;

_transferFrom2

Transfers the given amount of asset from sender to this contract via ERC20 transfer with Permit2 fallback.

function _transferFrom2(bytes calldata data) internal;

_approveManager

Approves this contract to manage the position of msg.sender via EIP712 signature.

function _approveManager(bytes calldata data) internal;

_supply

Supplies amount of asset of onBehalf using permit2 in a single tx. The supplied amount cannot be used as collateral but is eligible for the peer-to-peer matching.

function _supply(bytes calldata data) internal;

_supplyCollateral

Supplies amount of asset collateral to the pool on behalf of onBehalf.

function _supplyCollateral(bytes calldata data) internal;

_borrow

Borrows amount of asset on behalf of the sender. Sender must have previously approved the bulker as their manager on Morpho.

function _borrow(bytes calldata data) internal;

_repay

Repays amount of asset on behalf of onBehalf.

function _repay(bytes calldata data) internal;

_withdraw

Withdraws amount of asset on behalf of onBehalf. Sender must have previously approved the bulker as their manager on Morpho.

function _withdraw(bytes calldata data) internal;

_withdrawCollateral

Withdraws amount of asset on behalf of sender. Sender must have previously approved the bulker as their manager on Morpho.

function _withdrawCollateral(bytes calldata data) internal;

_wrapEth

Wraps the given input of ETH to WETH.

function _wrapEth(bytes calldata data) internal;

_unwrapEth

Unwraps the given input of WETH to ETH.

function _unwrapEth(bytes calldata data) internal;

_wrapStEth

Wraps the given input of stETH to wstETH.

function _wrapStEth(bytes calldata data) internal;

_unwrapStEth

Unwraps the given input of wstETH to stETH.

function _unwrapStEth(bytes calldata data) internal;

_skim

Sends any ERC20 in this contract to the receiver.

function _skim(bytes calldata data) internal;

_claimRewards

Claims rewards for the given assets, on behalf of an address, sending the funds to the given address.

function _claimRewards(bytes calldata data) internal;

_approveMaxToMorpho

Gives the max approval to the Morpho contract to spend the given asset if not already approved.

function _approveMaxToMorpho(address asset) internal;

SupplyVault

Git Source

Inherits: ISupplyVault, ERC4626UpgradeableSafe, Ownable2StepUpgradeable

Author: Morpho Labs

ERC4626-upgradeable Tokenized Vault implementation for Morpho-Aave V3.

This vault is not fully compliant to EIP-4626 because maxDeposit & maxMint do not take into account the underlying market's pause status and AaveV3's supply cap. Symmetrically, maxWithdraw & maxRedeem do not take into account the underlying market's pause status and liquidity.

State Variables

_MORPHO

The main Morpho contract.

IMorpho internal immutable _MORPHO;

_maxIterations

The max iterations to use when this vault interacts with Morpho.

uint96 internal _maxIterations;

_recipient

The recipient of the rewards that will redistribute them to vault's users.

address internal _recipient;

__gap

This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain. See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps

uint256[48] private __gap;

Functions

constructor

Initializes network-wide immutables.

The implementation contract disables initialization upon deployment to avoid being hijacked.

constructor(address morpho);

Parameters

NameTypeDescription
morphoaddressThe address of the main Morpho contract.

initialize

Initializes the vault.

function initialize(
    address newUnderlying,
    address newRecipient,
    string calldata name,
    string calldata symbol,
    uint256 initialDeposit,
    uint96 newMaxIterations
) external initializer;

Parameters

NameTypeDescription
newUnderlyingaddressThe address of the underlying market to supply through this vault to Morpho.
newRecipientaddressThe recipient to receive skimmed funds.
namestringThe name of the ERC20 token associated to this tokenized vault.
symbolstringThe symbol of the ERC20 token associated to this tokenized vault.
initialDeposituint256The amount of the initial deposit used to prevent pricePerShare manipulation.
newMaxIterationsuint96The max iterations to use when this vault interacts with Morpho.

skim

Transfers the given ERC20 tokens to the vault recipient.

This is meant to be used to transfer rewards that are claimed to the vault or rescue tokens. The vault is not intended to hold any ERC20 tokens between calls.

function skim(address[] calldata tokens) external;

setMaxIterations

Sets the max iterations to use when this vault interacts with Morpho.

function setMaxIterations(uint96 newMaxIterations) external onlyOwner;

setRecipient

Sets the recipient for the skim function.

function setRecipient(address newRecipient) external onlyOwner;

MORPHO

The address of the Morpho contract this vault utilizes.

function MORPHO() external view returns (IMorpho);

recipient

The recipient of any ERC20 tokens skimmed from this contract.

function recipient() external view returns (address);

maxIterations

The max iterations to use when this vault interacts with Morpho.

function maxIterations() external view returns (uint96);

totalAssets

The amount of assets in the vault.

function totalAssets() public view virtual override(IERC4626Upgradeable, ERC4626Upgradeable) returns (uint256);

_deposit

Used in mint or deposit to deposit the underlying asset to Morpho.

function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual override;

_withdraw

Used in redeem or withdraw to withdraw the underlying asset from Morpho.

function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)
    internal
    virtual
    override;

_setMaxIterations

Sets the max iterations to use when this vault interacts with Morpho.

function _setMaxIterations(uint96 newMaxIterations) internal;

_setRecipient

Sets the recipient for the skim function.

function _setRecipient(address newRecipient) internal;

WETHGateway

Git Source

Inherits: IWETHGateway

Author: Morpho Labs

A contract allowing to wrap and unwrap ETH when interacting with Morpho.

State Variables

_WETH

The address of the WETH contract.

address internal constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

_MORPHO_DAO

The address of the Morpho DAO.

address internal constant _MORPHO_DAO = 0xcBa28b38103307Ec8dA98377ffF9816C164f9AFa;

_MORPHO

The address of the Morpho protocol.

IMorpho internal immutable _MORPHO;

Functions

constructor

Contract constructor.

constructor(address morpho);

Parameters

NameTypeDescription
morphoaddressThe address of the Morpho protocol.

WETH

Returns the address of the WETH contract.

function WETH() external pure returns (address);

MORPHO

Returns the address of the Morpho protocol.

function MORPHO() external view returns (address);

MORPHO_DAO

Returns the address of the Morpho DAO.

function MORPHO_DAO() external pure returns (address);

skim

Transfers this contract's given ERC20 balance to the Morpho DAO, to avoid having funds stuck.

function skim(address underlying) external;

supplyETH

Wraps msg.value ETH in WETH and supplies them to Morpho on behalf of onBehalf.

function supplyETH(address onBehalf, uint256 maxIterations) external payable returns (uint256);

Returns

NameTypeDescription
<none>uint256The actual amount supplied (in wei).

supplyCollateralETH

Wraps msg.value ETH in WETH and supplies them as collateral to Morpho on behalf of onBehalf.

function supplyCollateralETH(address onBehalf) external payable returns (uint256);

Returns

NameTypeDescription
<none>uint256The actual amount supplied as collateral (in wei).

borrowETH

Borrows WETH on behalf of msg.sender, unwraps the ETH and sends them to receiver. Note: msg.sender must have approved this contract to be its manager.

function borrowETH(uint256 amount, address receiver, uint256 maxIterations) external returns (uint256 borrowed);

Returns

NameTypeDescription
borroweduint256The actual amount borrowed (in wei).

repayETH

Wraps msg.value ETH in WETH and repays onBehalf's debt on Morpho.

function repayETH(address onBehalf) external payable returns (uint256 repaid);

Returns

NameTypeDescription
repaiduint256The actual amount repaid (in wei).

withdrawETH

Withdraws WETH up to amount on behalf of msg.sender, unwraps it to WETH and sends it to receiver. Note: msg.sender must have approved this contract to be its manager.

function withdrawETH(uint256 amount, address receiver, uint256 maxIterations) external returns (uint256 withdrawn);

Returns

NameTypeDescription
withdrawnuint256The actual amount withdrawn (in wei).

withdrawCollateralETH

Withdraws WETH as collateral up to amount on behalf of msg.sender, unwraps it to WETH and sends it to receiver. Note: msg.sender must have approved this contract to be its manager.

function withdrawCollateralETH(uint256 amount, address receiver) external returns (uint256 withdrawn);

Returns

NameTypeDescription
withdrawnuint256The actual collateral amount withdrawn (in wei).

receive

Only the WETH contract is allowed to transfer ETH to this contracts.

receive() external payable;

_wrapETH

Wraps amount of ETH to WETH.

function _wrapETH(uint256 amount) internal;

_unwrapAndTransferETH

Unwraps amount of WETH to ETH and transfers it to receiver.

function _unwrapAndTransferETH(uint256 amount, address receiver) internal;

Errors

OnlyWETH

Thrown when another address than WETH sends ETH to the contract.

error OnlyWETH();

AddressIsZero

Thrown when the morpho address passed in the constructor is zero.

error AddressIsZero();

AmountIsZero

Thrown when the amount used is zero.

error AmountIsZero();

Contents

Contents

IAToken

Git Source

Inherits: IERC20, IScaledBalanceToken, IInitializableAToken

Author: Aave

Defines the basic interface for an AToken.

Aave's IAToken inherit IERC20 from OZ, using pragma 0.8.10. This interface is copied to enable compilation using a different pragma.

Functions

mint

Mints amount aTokens to user

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

Parameters

NameTypeDescription
calleraddressThe address performing the mint
onBehalfOfaddressThe address of the user that will receive the minted aTokens
amountuint256The amount of tokens getting minted
indexuint256The next 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

In some instances, the mint event could be emitted from a burn transaction if the amount to burn is less than the interest that the user accrued

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

Parameters

NameTypeDescription
fromaddressThe address from which the aTokens will be burned
receiverOfUnderlyingaddressThe address that will receive the underlying
amountuint256The amount being burned
indexuint256The next 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 next 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 Pool to transfer assets in borrow(), withdraw() and flashLoan()

function transferUnderlyingTo(address target, uint256 amount) external;

Parameters

NameTypeDescription
targetaddressThe recipient of the underlying
amountuint256The amount getting transferred

handleRepayment

Handles the underlying received by the aToken after the transfer has been completed.

The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying to receive LM rewards. In that case, handleRepayment() would perform the staking of the underlying asset.

function handleRepayment(address user, address onBehalfOf, uint256 amount) external;

Parameters

NameTypeDescription
useraddressThe user executing the repayment
onBehalfOfaddressThe address of the user who will get his debt reduced/removed
amountuint256The amount getting repaid

permit

Allow passing a signed message to approve spending

implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md

function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
    external;

Parameters

NameTypeDescription
owneraddressThe owner of the funds
spenderaddressThe spender
valueuint256The amount
deadlineuint256The deadline timestamp, type(uint256).max for max deadline
vuint8Signature param
rbytes32Signature param
sbytes32Signature param

UNDERLYING_ASSET_ADDRESS

Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)

function UNDERLYING_ASSET_ADDRESS() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the underlying asset

RESERVE_TREASURY_ADDRESS

Returns the address of the Aave treasury, receiving the fees on this aToken.

function RESERVE_TREASURY_ADDRESS() external view returns (address);

Returns

NameTypeDescription
<none>addressAddress of the Aave treasury

DOMAIN_SEPARATOR

Get the domain separator for the token

Return cached value if chainId matches cache, otherwise recomputes separator

function DOMAIN_SEPARATOR() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The domain separator of the token at current chain

nonces

Returns the nonce for owner.

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

Parameters

NameTypeDescription
owneraddressThe address of the owner

Returns

NameTypeDescription
<none>uint256The nonce of the owner

rescueTokens

Rescue and transfer tokens locked in this contract

function rescueTokens(address token, address to, uint256 amount) external;

Parameters

NameTypeDescription
tokenaddressThe address of the token
toaddressThe address of the recipient
amountuint256The amount of token to transfer

Events

BalanceTransfer

Emitted during the transfer action

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

IPoolToken

Git Source

Functions

UNDERLYING_ASSET_ADDRESS

Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)

function UNDERLYING_ASSET_ADDRESS() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the underlying asset

Contents

IBulkerGateway

Git Source

Functions

WETH

function WETH() external pure returns (address);

stETH

function stETH() external pure returns (address);

wstETH

function wstETH() external pure returns (address);

MORPHO

function MORPHO() external view returns (address);

execute

function execute(ActionType[] calldata actions, bytes[] calldata data) external payable;

Errors

InconsistentParameters

Thrown when execution parameters don't have the same length.

error InconsistentParameters(uint256 nbActions, uint256 nbData);

OnlyWETH

Thrown when another address than WETH sends ETH to the contract.

error OnlyWETH();

AddressIsZero

Thrown when an address used as parameter is the zero address.

error AddressIsZero();

AddressIsBulker

Thrown when an address parameter is the bulker's address.

error AddressIsBulker();

AmountIsZero

Thrown when an amount used as parameter is zero.

error AmountIsZero();

UnsupportedAction

Thrown when the action is unsupported.

error UnsupportedAction(ActionType action);

Enums

ActionType

enum ActionType {
    APPROVE2,
    TRANSFER_FROM2,
    APPROVE_MANAGER,
    SUPPLY,
    SUPPLY_COLLATERAL,
    BORROW,
    REPAY,
    WITHDRAW,
    WITHDRAW_COLLATERAL,
    WRAP_ETH,
    UNWRAP_ETH,
    WRAP_ST_ETH,
    UNWRAP_ST_ETH,
    SKIM,
    CLAIM_REWARDS
}

ILido

Git Source

Functions

getPooledEthByShares

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

getCurrentStakeLimit

function getCurrentStakeLimit() external view returns (uint256);

submit

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

ISupplyVault

Git Source

Inherits: IERC4626Upgradeable

Functions

MORPHO

function MORPHO() external view returns (IMorpho);

recipient

function recipient() external view returns (address);

maxIterations

function maxIterations() external view returns (uint96);

skim

function skim(address[] calldata tokens) external;

setMaxIterations

function setMaxIterations(uint96 newMaxIterations) external;

setRecipient

function setRecipient(address newRecipient) external;

Events

MaxIterationsSet

Emitted when max iterations is set.

event MaxIterationsSet(uint96 maxIterations);

RecipientSet

Emitted when the recipient is set.

event RecipientSet(address indexed recipient);

Skimmed

Emitted when tokens are skimmed to recipient.

event Skimmed(address indexed token, address indexed recipient, uint256 amount);

Errors

AddressIsZero

Thrown when an address used as parameter is the zero address.

error AddressIsZero();

InitialDepositIsZero

Thrown when the initial deposit at initialization is zero.

error InitialDepositIsZero();

IWETH

Git Source

Functions

deposit

function deposit() external payable;

withdraw

function withdraw(uint256 wad) external;

approve

function approve(address guy, uint256 wad) external returns (bool);

transferFrom

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

IWETHGateway

Git Source

Functions

WETH

function WETH() external pure returns (address);

MORPHO

function MORPHO() external view returns (address);

MORPHO_DAO

function MORPHO_DAO() external pure returns (address);

skim

function skim(address erc20) external;

supplyETH

function supplyETH(address onBehalf, uint256 maxIterations) external payable returns (uint256 supplied);

supplyCollateralETH

function supplyCollateralETH(address onBehalf) external payable returns (uint256 supplied);

borrowETH

function borrowETH(uint256 amount, address receiver, uint256 maxIterations) external returns (uint256 borrowed);

repayETH

function repayETH(address onBehalf) external payable returns (uint256 repaid);

withdrawETH

function withdrawETH(uint256 amount, address receiver, uint256 maxIterations) external returns (uint256 withdrawn);

withdrawCollateralETH

function withdrawCollateralETH(uint256 amount, address receiver) external returns (uint256 withdrawn);

IWSTETH

Git Source

Functions

DOMAIN_SEPARATOR

function DOMAIN_SEPARATOR() external view returns (bytes32);

allowance

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

approve

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

balanceOf

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

decimals

function decimals() external view returns (uint8);

decreaseAllowance

function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);

getStETHByWstETH

function getStETHByWstETH(uint256 wstETHAmount) external view returns (uint256);

getWstETHByStETH

function getWstETHByStETH(uint256 stETHAmount) external view returns (uint256);

increaseAllowance

function increaseAllowance(address spender, uint256 addedValue) external returns (bool);

name

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

nonces

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

permit

function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
    external;

stETH

function stETH() external view returns (address);

stEthPerToken

function stEthPerToken() external view returns (uint256);

symbol

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

tokensPerStEth

function tokensPerStEth() external view returns (uint256);

totalSupply

function totalSupply() external view returns (uint256);

transfer

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

transferFrom

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

unwrap

function unwrap(uint256 wstETHAmount) external returns (uint256);

wrap

function wrap(uint256 stETHAmount) external returns (uint256);

IMorphoGetters

Git Source

Functions

DOMAIN_SEPARATOR

function DOMAIN_SEPARATOR() external view returns (bytes32);

pool

function pool() external view returns (address);

addressesProvider

function addressesProvider() external view returns (address);

eModeCategoryId

function eModeCategoryId() external view returns (uint256);

market

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

marketsCreated

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

scaledCollateralBalance

function scaledCollateralBalance(address underlying, address user) external view returns (uint256);

scaledP2PBorrowBalance

function scaledP2PBorrowBalance(address underlying, address user) external view returns (uint256);

scaledP2PSupplyBalance

function scaledP2PSupplyBalance(address underlying, address user) external view returns (uint256);

scaledPoolBorrowBalance

function scaledPoolBorrowBalance(address underlying, address user) external view returns (uint256);

scaledPoolSupplyBalance

function scaledPoolSupplyBalance(address underlying, address user) external view returns (uint256);

supplyBalance

function supplyBalance(address underlying, address user) external view returns (uint256);

borrowBalance

function borrowBalance(address underlying, address user) external view returns (uint256);

collateralBalance

function collateralBalance(address underlying, address user) external view returns (uint256);

userCollaterals

function userCollaterals(address user) external view returns (address[] memory);

userBorrows

function userBorrows(address user) external view returns (address[] memory);

isManagedBy

function isManagedBy(address delegator, address manager) external view returns (bool);

userNonce

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

defaultIterations

function defaultIterations() external view returns (Types.Iterations memory);

positionsManager

function positionsManager() external view returns (address);

rewardsManager

function rewardsManager() external view returns (address);

treasuryVault

function treasuryVault() external view returns (address);

isClaimRewardsPaused

function isClaimRewardsPaused() external view returns (bool);

updatedIndexes

function updatedIndexes(address underlying) external view returns (Types.Indexes256 memory);

liquidityData

function liquidityData(address user) external view returns (Types.LiquidityData memory);

getNext

function getNext(address underlying, Types.Position position, address user) external view returns (address);

getBucketsMask

function getBucketsMask(address underlying, Types.Position position) external view returns (uint256);

IMorphoSetters

Git Source

Functions

createMarket

function createMarket(address underlying, uint16 reserveFactor, uint16 p2pIndexCursor) external;

increaseP2PDeltas

function increaseP2PDeltas(address underlying, uint256 amount) external;

claimToTreasury

function claimToTreasury(address[] calldata underlyings, uint256[] calldata amounts) external;

setPositionsManager

function setPositionsManager(address positionsManager) external;

setRewardsManager

function setRewardsManager(address rewardsManager) external;

setTreasuryVault

function setTreasuryVault(address treasuryVault) external;

setDefaultIterations

function setDefaultIterations(Types.Iterations memory defaultIterations) external;

setP2PIndexCursor

function setP2PIndexCursor(address underlying, uint16 p2pIndexCursor) external;

setReserveFactor

function setReserveFactor(address underlying, uint16 newReserveFactor) external;

setAssetIsCollateralOnPool

function setAssetIsCollateralOnPool(address underlying, bool isCollateral) external;

setAssetIsCollateral

function setAssetIsCollateral(address underlying, bool isCollateral) external;

setIsClaimRewardsPaused

function setIsClaimRewardsPaused(bool isPaused) external;

setIsPaused

function setIsPaused(address underlying, bool isPaused) external;

setIsPausedForAllMarkets

function setIsPausedForAllMarkets(bool isPaused) external;

setIsSupplyPaused

function setIsSupplyPaused(address underlying, bool isPaused) external;

setIsSupplyCollateralPaused

function setIsSupplyCollateralPaused(address underlying, bool isPaused) external;

setIsBorrowPaused

function setIsBorrowPaused(address underlying, bool isPaused) external;

setIsRepayPaused

function setIsRepayPaused(address underlying, bool isPaused) external;

setIsWithdrawPaused

function setIsWithdrawPaused(address underlying, bool isPaused) external;

setIsWithdrawCollateralPaused

function setIsWithdrawCollateralPaused(address underlying, bool isPaused) external;

setIsLiquidateBorrowPaused

function setIsLiquidateBorrowPaused(address underlying, bool isPaused) external;

setIsLiquidateCollateralPaused

function setIsLiquidateCollateralPaused(address underlying, bool isPaused) external;

setIsP2PDisabled

function setIsP2PDisabled(address underlying, bool isP2PDisabled) external;

setIsDeprecated

function setIsDeprecated(address underlying, bool isDeprecated) external;

IMorpho

Git Source

Inherits: IMorphoGetters, IMorphoSetters

Functions

initialize

function initialize(
    address addressesProvider,
    uint8 eModeCategoryId,
    address newPositionsManager,
    Types.Iterations memory newDefaultIterations
) external;

supply

function supply(address underlying, uint256 amount, address onBehalf, uint256 maxIterations)
    external
    returns (uint256 supplied);

supplyWithPermit

function supplyWithPermit(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 maxIterations,
    uint256 deadline,
    Types.Signature calldata signature
) external returns (uint256 supplied);

supplyCollateral

function supplyCollateral(address underlying, uint256 amount, address onBehalf) external returns (uint256 supplied);

supplyCollateralWithPermit

function supplyCollateralWithPermit(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 deadline,
    Types.Signature calldata signature
) external returns (uint256 supplied);

borrow

function borrow(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
    external
    returns (uint256 borrowed);

repay

function repay(address underlying, uint256 amount, address onBehalf) external returns (uint256 repaid);

repayWithPermit

function repayWithPermit(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 deadline,
    Types.Signature calldata signature
) external returns (uint256 repaid);

withdraw

function withdraw(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
    external
    returns (uint256 withdrawn);

withdrawCollateral

function withdrawCollateral(address underlying, uint256 amount, address onBehalf, address receiver)
    external
    returns (uint256 withdrawn);

approveManager

function approveManager(address manager, bool isAllowed) external;

approveManagerWithSig

function approveManagerWithSig(
    address delegator,
    address manager,
    bool isAllowed,
    uint256 nonce,
    uint256 deadline,
    Types.Signature calldata signature
) external;

liquidate

function liquidate(address underlyingBorrowed, address underlyingCollateral, address user, uint256 amount)
    external
    returns (uint256 repaid, uint256 seized);

claimRewards

function claimRewards(address[] calldata assets, address onBehalf)
    external
    returns (address[] memory rewardTokens, uint256[] memory claimedAmounts);

IPositionsManager

Git Source

Functions

supplyLogic

function supplyLogic(address underlying, uint256 amount, address from, address onBehalf, uint256 maxIterations)
    external
    returns (uint256 supplied);

supplyCollateralLogic

function supplyCollateralLogic(address underlying, uint256 amount, address from, address onBehalf)
    external
    returns (uint256 supplied);

borrowLogic

function borrowLogic(address underlying, uint256 amount, address borrower, address receiver, uint256 maxIterations)
    external
    returns (uint256 borrowed);

repayLogic

function repayLogic(address underlying, uint256 amount, address repayer, address onBehalf)
    external
    returns (uint256 repaid);

withdrawLogic

function withdrawLogic(address underlying, uint256 amount, address supplier, address receiver, uint256 maxIterations)
    external
    returns (uint256 withdrawn);

withdrawCollateralLogic

function withdrawCollateralLogic(address underlying, uint256 amount, address supplier, address receiver)
    external
    returns (uint256 withdrawn);

liquidateLogic

function liquidateLogic(
    address underlyingBorrowed,
    address underlyingCollateral,
    uint256 amount,
    address borrower,
    address liquidator
) external returns (uint256 liquidated, uint256 seized);

IRewardsManager

Git Source

Functions

MORPHO

function MORPHO() external view returns (address);

REWARDS_CONTROLLER

function REWARDS_CONTROLLER() external view returns (address);

getRewardData

function getRewardData(address asset, address reward)
    external
    view
    returns (uint256 startingIndex, uint256 index, uint256 lastUpdateTimestamp);

getUserData

function getUserData(address asset, address reward, address user)
    external
    view
    returns (uint256 index, uint256 accrued);

getAllUserRewards

function getAllUserRewards(address[] calldata assets, address user)
    external
    view
    returns (address[] memory rewardsList, uint256[] memory unclaimedAmounts);

getUserRewards

function getUserRewards(address[] calldata assets, address user, address reward) external view returns (uint256);

getUserAccruedRewards

function getUserAccruedRewards(address[] calldata assets, address user, address reward)
    external
    view
    returns (uint256 totalAccrued);

getUserAssetIndex

function getUserAssetIndex(address user, address asset, address reward) external view returns (uint256);

getAssetIndex

function getAssetIndex(address asset, address reward) external view returns (uint256 assetIndex);

claimRewards

function claimRewards(address[] calldata assets, address user)
    external
    returns (address[] memory rewardsList, uint256[] memory claimedAmounts);

updateUserRewards

function updateUserRewards(address user, address asset, uint256 userBalance) external;

Events

Accrued

Emitted when rewards of an asset are accrued on behalf of a user.

event Accrued(
    address indexed asset, address indexed reward, address indexed user, uint256 assetIndex, uint256 rewardsAccrued
);

Errors

OnlyMorpho

Thrown when only the main Morpho contract can call the function.

error OnlyMorpho();

InvalidAsset

Thrown when an invalid asset is passed to accrue rewards.

error InvalidAsset();

AddressIsZero

Thrown when the the zero address is passed as a parameter.

error AddressIsZero();

Structs

UserAssetBalance

struct UserAssetBalance {
    address asset;
    uint256 scaledBalance;
    uint256 scaledTotalSupply;
}

UserData

struct UserData {
    uint104 index;
    uint128 accrued;
}

RewardData

struct RewardData {
    uint104 startingIndex;
    uint104 index;
    uint32 lastUpdateTimestamp;
    mapping(address => UserData) usersData;
}

Contents

Constants

Git Source

Author: Morpho Labs

Library exposing constants used in Morpho.

State Variables

NO_REFERRAL_CODE

The referral code used for Aave.

uint8 internal constant NO_REFERRAL_CODE = 0;

VARIABLE_INTEREST_MODE

The variable interest rate mode of Aave.

uint8 internal constant VARIABLE_INTEREST_MODE = 2;

DUST_THRESHOLD

The threshold under which the balance is swept to 0.

uint256 internal constant DUST_THRESHOLD = 1;

LT_LOWER_BOUND

A lower bound on the liquidation threshold values of all the listed assets.

uint256 internal constant LT_LOWER_BOUND = 10_00;

MAX_CLOSE_FACTOR

The maximum close factor used during liquidations (100%).

uint256 internal constant MAX_CLOSE_FACTOR = PercentageMath.PERCENTAGE_FACTOR;

DEFAULT_CLOSE_FACTOR

The default close factor used during liquidations (50%).

uint256 internal constant DEFAULT_CLOSE_FACTOR = PercentageMath.HALF_PERCENTAGE_FACTOR;

DEFAULT_LIQUIDATION_MAX_HF

Health factor below which the positions can be liquidated.

uint256 internal constant DEFAULT_LIQUIDATION_MAX_HF = WadRayMath.WAD;

DEFAULT_LIQUIDATION_MIN_HF

Health factor below which the positions can be liquidated, whether or not the price oracle sentinel allows the liquidation.

uint256 internal constant DEFAULT_LIQUIDATION_MIN_HF = 0.95e18;

EIP712_MSG_PREFIX

The prefix used for EIP-712 signature.

string internal constant EIP712_MSG_PREFIX = "\x19\x01";

EIP712_NAME

The name used for EIP-712 signature.

string internal constant EIP712_NAME = "Morpho-AaveV3";

EIP712_VERSION

The version used for EIP-712 signature.

string internal constant EIP712_VERSION = "0";

EIP712_DOMAIN_TYPEHASH

The domain typehash used for the EIP-712 signature.

bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

EIP712_AUTHORIZATION_TYPEHASH

The typehash for approveManagerWithSig Authorization used for the EIP-712 signature.

bytes32 internal constant EIP712_AUTHORIZATION_TYPEHASH =
    keccak256("Authorization(address delegator,address manager,bool isAllowed,uint256 nonce,uint256 deadline)");

MAX_VALID_ECDSA_S

The highest valid value for s in an ECDSA signature pair (0 < s < secp256k1n ÷ 2 + 1).

uint256 internal constant MAX_VALID_ECDSA_S = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

DeltasLib

Git Source

Author: Morpho Labs

Library used to ease delta reads and writes.

Functions

increaseP2P

Increases the peer-to-peer amounts following a promotion.

function increaseP2P(
    Types.Deltas storage deltas,
    address underlying,
    uint256 promoted,
    uint256 amount,
    Types.Indexes256 memory indexes,
    bool borrowSide
) internal returns (uint256 p2pBalanceIncrease);

Parameters

NameTypeDescription
deltasTypes.DeltasThe market deltas to update.
underlyingaddressThe underlying address.
promoteduint256The amount to increase the promoted side peer-to-peer total (in underlying). Must be lower than or equal to amount.
amountuint256The amount to increase the opposite side peer-to-peer total (in underlying).
indexesTypes.Indexes256The current indexes.
borrowSideboolTrue if this follows borrower promotions. False for supplier promotions.

Returns

NameTypeDescription
p2pBalanceIncreaseuint256The scaled balance amount in peer-to-peer to increase.

decreaseP2P

Decreases the peer-to-peer amounts following a demotion.

function decreaseP2P(
    Types.Deltas storage deltas,
    address underlying,
    uint256 demoted,
    uint256 amount,
    Types.Indexes256 memory indexes,
    bool borrowSide
) internal;

Parameters

NameTypeDescription
deltasTypes.DeltasThe market deltas to update.
underlyingaddressThe underlying address.
demoteduint256The amount to decrease the demoted side peer-to-peer total (in underlying). Must be lower than or equal to amount.
amountuint256The amount to decrease the opposite side peer-to-peer total (in underlying).
indexesTypes.Indexes256The current indexes.
borrowSideboolTrue if this follows borrower demotions. False for supplier demotions.

Errors

Git Source

Author: Morpho Labs

Library exposing errors used in Morpho.

Errors

MarketNotCreated

Thrown when interacting with a market that is not created.

error MarketNotCreated();

MarketAlreadyCreated

Thrown when creating a market that is already created.

error MarketAlreadyCreated();

MarketIsNotListedOnAave

Thrown when creating a market that is not listed on Aave.

error MarketIsNotListedOnAave();

SiloedBorrowMarket

Thrown when the market is in a siloed borrowing mode.

error SiloedBorrowMarket();

MarketLtTooLow

Thrown when the market liquidation threshold is too low to be created.

error MarketLtTooLow();

AddressIsZero

Thrown when the address used is the zero address.

error AddressIsZero();

AmountIsZero

Thrown when the amount used is zero.

error AmountIsZero();

DebtIsZero

Thrown when the user's debt is zero.

error DebtIsZero();

SupplyIsZero

Thrown when the user's supply is zero.

error SupplyIsZero();

CollateralIsZero

Thrown when the user's collateral is zero.

error CollateralIsZero();

PermissionDenied

Thrown when the manager is not approved by the delegator.

error PermissionDenied();

SupplyIsPaused

Thrown when supply is paused for the asset.

error SupplyIsPaused();

SupplyCollateralIsPaused

Thrown when supply collateral is paused for the asset.

error SupplyCollateralIsPaused();

BorrowIsPaused

Thrown when borrow is paused for the asset.

error BorrowIsPaused();

RepayIsPaused

Thrown when repay is paused for the asset.

error RepayIsPaused();

WithdrawIsPaused

Thrown when withdraw is paused for the asset.

error WithdrawIsPaused();

WithdrawCollateralIsPaused

Thrown when withdraw collateral is paused for the asset.

error WithdrawCollateralIsPaused();

LiquidateCollateralIsPaused

Thrown when liquidate is paused for the collateral asset.

error LiquidateCollateralIsPaused();

LiquidateBorrowIsPaused

Thrown when liquidate is paused for the borrow asset

error LiquidateBorrowIsPaused();

ClaimRewardsPaused

Thrown when claim rewards is paused.

error ClaimRewardsPaused();

MarketIsDeprecated

Thrown when unpausing the borrow of a market that is deprecated.

error MarketIsDeprecated();

BorrowNotPaused

Thrown when deprecating a market that is not paused.

error BorrowNotPaused();

BorrowNotEnabled

Thrown when the market is not enabled on Aave.

error BorrowNotEnabled();

SentinelBorrowNotEnabled

Thrown when the oracle sentinel is set and disables borrowing.

error SentinelBorrowNotEnabled();

InconsistentEMode

Thrown when borrowing an asset that is not in Morpho's e-mode category.

error InconsistentEMode();

UnauthorizedBorrow

Thrown when a borrow would leave the user undercollateralized.

error UnauthorizedBorrow();

UnauthorizedWithdraw

Thrown when a withdraw would leave the user undercollateralized.

error UnauthorizedWithdraw();

UnauthorizedLiquidate

Thrown when the liquidatation is not authorized because of a collateralization ratio too high.

error UnauthorizedLiquidate();

SentinelLiquidateNotEnabled

Thrown when the oracle sentinel is set and disables liquidating.

error SentinelLiquidateNotEnabled();

AssetNotCollateralOnPool

Thrown when (un)setting a market as collateral on Morpho while it is not a collateral on Aave.

error AssetNotCollateralOnPool();

AssetNotCollateralOnMorpho

Thrown when supplying an asset as collateral while it is not a collateral on Morpho.

error AssetNotCollateralOnMorpho();

AssetIsCollateralOnMorpho

Thrown when (un)setting a market as collateral on Aave while it is a collateral on Morpho.

error AssetIsCollateralOnMorpho();

SetAsCollateralOnPoolButMarketNotCreated

Thrown when setting a market as collateral on Aave while the market is not created on Morpho.

error SetAsCollateralOnPoolButMarketNotCreated();

ExceedsMaxBasisPoints

Thrown when the value exceeds the maximum basis points value (100% = 10000).

error ExceedsMaxBasisPoints();

InvalidValueS

Thrown when the s part of the ECDSA signature is invalid.

error InvalidValueS();

InvalidValueV

Thrown when the v part of the ECDSA signature is invalid.

error InvalidValueV();

InvalidSignatory

Thrown when the signatory of the ECDSA signature is invalid.

error InvalidSignatory();

InvalidNonce

Thrown when the nonce is invalid.

error InvalidNonce();

SignatureExpired

Thrown when the signature is expired

error SignatureExpired();

ExceedsBorrowCap

Thrown when the borrow cap on Aave is exceeded.

error ExceedsBorrowCap();

Events

Git Source

Author: Morpho Labs

Library exposing events used in Morpho.

Events

Supplied

Emitted when a supply happens.

event Supplied(
    address indexed from,
    address indexed onBehalf,
    address indexed underlying,
    uint256 amount,
    uint256 scaledOnPool,
    uint256 scaledInP2P
);

CollateralSupplied

Emitted when a supply collateral happens.

event CollateralSupplied(
    address indexed from, address indexed onBehalf, address indexed underlying, uint256 amount, uint256 scaledBalance
);

Borrowed

Emitted when a borrow happens.

event Borrowed(
    address caller,
    address indexed onBehalf,
    address indexed receiver,
    address indexed underlying,
    uint256 amount,
    uint256 scaledOnPool,
    uint256 scaledInP2P
);

Repaid

Emitted when a repay happens.

event Repaid(
    address indexed repayer,
    address indexed onBehalf,
    address indexed underlying,
    uint256 amount,
    uint256 scaledOnPool,
    uint256 scaledInP2P
);

Withdrawn

Emitted when a withdraw happens.

event Withdrawn(
    address caller,
    address indexed onBehalf,
    address indexed receiver,
    address indexed underlying,
    uint256 amount,
    uint256 scaledOnPool,
    uint256 scaledInP2P
);

CollateralWithdrawn

Emitted when a withdraw collateral happens.

event CollateralWithdrawn(
    address caller,
    address indexed onBehalf,
    address indexed receiver,
    address indexed underlying,
    uint256 amount,
    uint256 scaledBalance
);

Liquidated

Emitted when a liquidate happens.

event Liquidated(
    address indexed liquidator,
    address indexed borrower,
    address indexed underlyingBorrowed,
    uint256 amountLiquidated,
    address underlyingCollateral,
    uint256 amountSeized
);

ManagerApproval

Emitted when a manager is approved or unapproved to act on behalf of a delegator.

event ManagerApproval(address indexed delegator, address indexed manager, bool isAllowed);

SupplyPositionUpdated

Emitted when a supply position is updated.

event SupplyPositionUpdated(
    address indexed user, address indexed underlying, uint256 scaledOnPool, uint256 scaledInP2P
);

BorrowPositionUpdated

Emitted when a borrow position is updated.

event BorrowPositionUpdated(
    address indexed user, address indexed underlying, uint256 scaledOnPool, uint256 scaledInP2P
);

P2PSupplyDeltaUpdated

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

event P2PSupplyDeltaUpdated(address indexed underlying, uint256 scaledDelta);

P2PBorrowDeltaUpdated

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

event P2PBorrowDeltaUpdated(address indexed underlying, uint256 scaledDelta);

P2PTotalsUpdated

Emitted when the peer-to-peer total amounts are updated.

event P2PTotalsUpdated(address indexed underlying, uint256 scaledTotalSupplyP2P, uint256 scaledTotalBorrowP2P);

RewardsClaimed

Emitted when a rewards are claimed.

event RewardsClaimed(
    address indexed claimer, address indexed onBehalf, address indexed rewardToken, uint256 amountClaimed
);

IsCollateralSet

Emitted when the collateral status of the underlying market is set to isCollateral.

event IsCollateralSet(address indexed underlying, bool isCollateral);

IsClaimRewardsPausedSet

Emitted when the claim rewards status is set to isPaused.

event IsClaimRewardsPausedSet(bool isPaused);

IsSupplyPausedSet

Emitted when the supply pause status of the underlying market is set to isPaused.

event IsSupplyPausedSet(address indexed underlying, bool isPaused);

IsSupplyCollateralPausedSet

Emitted when the supply collateral pause status of the underlying market is set to isPaused.

event IsSupplyCollateralPausedSet(address indexed underlying, bool isPaused);

IsBorrowPausedSet

Emitted when the borrow pause status of the underlying market is set to isPaused.

event IsBorrowPausedSet(address indexed underlying, bool isPaused);

IsWithdrawPausedSet

Emitted when the withdraw pause status of the underlying market is set to isPaused.

event IsWithdrawPausedSet(address indexed underlying, bool isPaused);

IsWithdrawCollateralPausedSet

Emitted when the withdraw collateral pause status of the underlying market is set to isPaused.

event IsWithdrawCollateralPausedSet(address indexed underlying, bool isPaused);

IsRepayPausedSet

Emitted when the repay pause status of the underlying market is set to isPaused.

event IsRepayPausedSet(address indexed underlying, bool isPaused);

IsLiquidateCollateralPausedSet

Emitted when the liquidate collateral pause status of the underlying market is set to isPaused.

event IsLiquidateCollateralPausedSet(address indexed underlying, bool isPaused);

IsLiquidateBorrowPausedSet

Emitted when the liquidate borrow pause status of the underlying market is set to isPaused.

event IsLiquidateBorrowPausedSet(address indexed underlying, bool isPaused);

P2PDeltasIncreased

Emitted when an _increaseP2PDeltas is triggered.

event P2PDeltasIncreased(address indexed underlying, uint256 amount);

MarketCreated

Emitted when a new market is created.

event MarketCreated(address indexed underlying);

DefaultIterationsSet

Emitted when the default iterations are set.

event DefaultIterationsSet(uint128 repay, uint128 withdraw);

PositionsManagerSet

Emitted when the positions manager is set.

event PositionsManagerSet(address indexed positionsManager);

RewardsManagerSet

Emitted when the rewards manager is set.

event RewardsManagerSet(address indexed rewardsManager);

TreasuryVaultSet

Emitted when the treasury vault is set.

event TreasuryVaultSet(address indexed treasuryVault);

ReserveFactorSet

Emitted when the reserve factor is set.

event ReserveFactorSet(address indexed underlying, uint16 reserveFactor);

P2PIndexCursorSet

Emitted when the peer-to-peer index cursor is set.

event P2PIndexCursorSet(address indexed underlying, uint16 p2pIndexCursor);

IsP2PDisabledSet

Emitted when the peer-to-peer disabled status is set.

event IsP2PDisabledSet(address indexed underlying, bool isP2PDisabled);

IsDeprecatedSet

Emitted when the deprecation status is set.

event IsDeprecatedSet(address indexed underlying, bool isDeprecated);

IndexesUpdated

Emitted when the indexes are updated.

event IndexesUpdated(
    address indexed underlying,
    uint256 poolSupplyIndex,
    uint256 p2pSupplyIndex,
    uint256 poolBorrowIndex,
    uint256 p2pBorrowIndex
);

IdleSupplyUpdated

Emitted when the idle supply is updated.

event IdleSupplyUpdated(address indexed underlying, uint256 idleSupply);

ReserveFeeClaimed

Emitted when the reserve fee is claimed.

event ReserveFeeClaimed(address indexed underlying, uint256 claimed);

UserNonceIncremented

Emitted when a user nonce is incremented.

event UserNonceIncremented(address indexed caller, address indexed signatory, uint256 usedNonce);

InterestRatesLib

Git Source

Author: Morpho Labs

Library helping to compute the new peer-to-peer indexes.

Functions

computeP2PIndexes

Computes and returns the new peer-to-peer indexes of a market given its parameters.

function computeP2PIndexes(Types.IndexesParams memory params)
    internal
    pure
    returns (uint256 newP2PSupplyIndex, uint256 newP2PBorrowIndex);

Returns

NameTypeDescription
newP2PSupplyIndexuint256The peer-to-peer supply index.
newP2PBorrowIndexuint256The peer-to-peer borrow index.

computeGrowthFactors

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

function computeGrowthFactors(
    uint256 newPoolSupplyIndex,
    uint256 newPoolBorrowIndex,
    uint256 lastPoolSupplyIndex,
    uint256 lastPoolBorrowIndex,
    uint256 p2pIndexCursor,
    uint256 reserveFactor
) internal pure returns (Types.GrowthFactors memory growthFactors);

Parameters

NameTypeDescription
newPoolSupplyIndexuint256The pool's current supply index.
newPoolBorrowIndexuint256The pool's current borrow index.
lastPoolSupplyIndexuint256The pool's last supply index.
lastPoolBorrowIndexuint256The pool's last borrow index.
p2pIndexCursoruint256The peer-to-peer index cursor for the given market.
reserveFactoruint256The reserve factor of the given market.

Returns

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

computeP2PIndex

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

function computeP2PIndex(
    uint256 poolGrowthFactor,
    uint256 p2pGrowthFactor,
    Types.MarketSideIndexes256 memory lastIndexes,
    uint256 scaledDelta,
    uint256 scaledP2PTotal,
    uint256 proportionIdle
) internal pure returns (uint256);

Parameters

NameTypeDescription
poolGrowthFactoruint256The pool growth factor.
p2pGrowthFactoruint256The peer-to-peer growth factor.
lastIndexesTypes.MarketSideIndexes256The last pool & peer-to-peer indexes.
scaledDeltauint256The last scaled peer-to-peer delta (pool unit).
scaledP2PTotaluint256The last scaled total peer-to-peer amount (P2P unit).
proportionIdleuint256

Returns

NameTypeDescription
<none>uint256newP2PIndex The updated peer-to-peer index (in ray).

MarketBalanceLib

Git Source

Author: Morpho Labs

Library used to ease market balance reads.

Functions

scaledPoolSupplyBalance

Returns the scaled pool supply balance of user given the marketBalances of a specific market.

function scaledPoolSupplyBalance(Types.MarketBalances storage marketBalances, address user)
    internal
    view
    returns (uint256);

scaledP2PSupplyBalance

Returns the scaled peer-to-peer supply balance of user given the marketBalances of a specific market.

function scaledP2PSupplyBalance(Types.MarketBalances storage marketBalances, address user)
    internal
    view
    returns (uint256);

scaledPoolBorrowBalance

Returns the scaled pool borrow balance of user given the marketBalances of a specific market.

function scaledPoolBorrowBalance(Types.MarketBalances storage marketBalances, address user)
    internal
    view
    returns (uint256);

scaledP2PBorrowBalance

Returns the scaled peer-to-peer borrow balance of user given the marketBalances of a specific market.

function scaledP2PBorrowBalance(Types.MarketBalances storage marketBalances, address user)
    internal
    view
    returns (uint256);

scaledCollateralBalance

Returns the scaled collateral balance of user given the marketBalances of a specific market.

function scaledCollateralBalance(Types.MarketBalances storage marketBalances, address user)
    internal
    view
    returns (uint256);

MarketLib

Git Source

Author: Morpho Labs

Library used to ease market reads and writes.

Functions

isCreated

Returns whether the market is created or not.

function isCreated(Types.Market storage market) internal view returns (bool);

isSupplyPaused

Returns whether supply is paused on market or not.

function isSupplyPaused(Types.Market storage market) internal view returns (bool);

isSupplyCollateralPaused

Returns whether supply collateral is paused on market or not.

function isSupplyCollateralPaused(Types.Market storage market) internal view returns (bool);

isBorrowPaused

Returns whether borrow is paused on market or not.

function isBorrowPaused(Types.Market storage market) internal view returns (bool);

isRepayPaused

Returns whether repay is paused on market or not.

function isRepayPaused(Types.Market storage market) internal view returns (bool);

isWithdrawPaused

Returns whether withdraw is paused on market or not.

function isWithdrawPaused(Types.Market storage market) internal view returns (bool);

isWithdrawCollateralPaused

Returns whether withdraw collateral is paused on market or not.

function isWithdrawCollateralPaused(Types.Market storage market) internal view returns (bool);

isLiquidateCollateralPaused

Returns whether liquidate collateral is paused on market or not.

function isLiquidateCollateralPaused(Types.Market storage market) internal view returns (bool);

isLiquidateBorrowPaused

Returns whether liquidate borrow is paused on market or not.

function isLiquidateBorrowPaused(Types.Market storage market) internal view returns (bool);

isDeprecated

Returns whether the market is deprecated or not.

function isDeprecated(Types.Market storage market) internal view returns (bool);

isP2PDisabled

Returns whether the peer-to-peer is disabled on market or not.

function isP2PDisabled(Types.Market storage market) internal view returns (bool);

setAssetIsCollateral

Sets the market as isCollateral on Morpho.

function setAssetIsCollateral(Types.Market storage market, bool isCollateral) internal;

setIsSupplyPaused

Sets the market supply pause status as isPaused on Morpho.

function setIsSupplyPaused(Types.Market storage market, bool isPaused) internal;

setIsSupplyCollateralPaused

Sets the market supply collateral pause status as isPaused on Morpho.

function setIsSupplyCollateralPaused(Types.Market storage market, bool isPaused) internal;

setIsBorrowPaused

Sets the market borrow pause status as isPaused on Morpho.

function setIsBorrowPaused(Types.Market storage market, bool isPaused) internal;

setIsRepayPaused

Sets the market repay pause status as isPaused on Morpho.

function setIsRepayPaused(Types.Market storage market, bool isPaused) internal;

setIsWithdrawPaused

Sets the market withdraw pause status as isPaused on Morpho.

function setIsWithdrawPaused(Types.Market storage market, bool isPaused) internal;

setIsWithdrawCollateralPaused

Sets the market withdraw collateral pause status as isPaused on Morpho.

function setIsWithdrawCollateralPaused(Types.Market storage market, bool isPaused) internal;

setIsLiquidateCollateralPaused

Sets the market liquidate collateral pause status as isPaused on Morpho.

function setIsLiquidateCollateralPaused(Types.Market storage market, bool isPaused) internal;

setIsLiquidateBorrowPaused

Sets the market liquidate borrow pause status as isPaused on Morpho.

function setIsLiquidateBorrowPaused(Types.Market storage market, bool isPaused) internal;

setIsDeprecated

Sets the market as deprecated on Morpho.

function setIsDeprecated(Types.Market storage market, bool deprecated) internal;

setIsP2PDisabled

Sets the market peer-to-peer as p2pDisabled on Morpho.

function setIsP2PDisabled(Types.Market storage market, bool p2pDisabled) internal;

setReserveFactor

Sets the market peer-to-peer reserve factor to reserveFactor.

function setReserveFactor(Types.Market storage market, uint16 reserveFactor) internal;

setP2PIndexCursor

Sets the market peer-to-peer index cursor to p2pIndexCursor.

function setP2PIndexCursor(Types.Market storage market, uint16 p2pIndexCursor) internal;

setIndexes

Sets the market indexes to indexes.

function setIndexes(Types.Market storage market, Types.Indexes256 memory indexes) internal;

getSupplyIndexes

Returns the supply indexes of market.

function getSupplyIndexes(Types.Market storage market)
    internal
    view
    returns (Types.MarketSideIndexes256 memory supplyIndexes);

getBorrowIndexes

Returns the borrow indexes of market.

function getBorrowIndexes(Types.Market storage market)
    internal
    view
    returns (Types.MarketSideIndexes256 memory borrowIndexes);

getIndexes

Returns the indexes of market.

function getIndexes(Types.Market storage market) internal view returns (Types.Indexes256 memory indexes);

getProportionIdle

Returns the proportion of idle supply in market over the total peer-to-peer amount in supply.

function getProportionIdle(Types.Market storage market) internal view returns (uint256);

increaseIdle

Increases the idle supply if the supply cap is reached in a breaking repay, and returns a new toSupply amount.

function increaseIdle(
    Types.Market storage market,
    address underlying,
    uint256 amount,
    DataTypes.ReserveData memory reserve,
    Types.Indexes256 memory indexes
) internal returns (uint256, uint256);

Parameters

NameTypeDescription
marketTypes.MarketThe market storage.
underlyingaddressThe underlying address.
amountuint256The amount to repay. (by supplying on pool)
reserveDataTypes.ReserveDataThe reserve data for the market.
indexesTypes.Indexes256

Returns

NameTypeDescription
<none>uint256The amount to supply to stay below the supply cap and the amount the idle supply was increased by.
<none>uint256

decreaseIdle

Decreases the idle supply.

function decreaseIdle(Types.Market storage market, address underlying, uint256 amount)
    internal
    returns (uint256, uint256);

Parameters

NameTypeDescription
marketTypes.MarketThe market storage.
underlyingaddressThe underlying address.
amountuint256The amount to borrow.

Returns

NameTypeDescription
<none>uint256The amount left to process and the processed amount.
<none>uint256

trueP2PSupply

Calculates the total quantity of underlyings truly supplied peer-to-peer on the given market.

function trueP2PSupply(Types.Market storage market, Types.Indexes256 memory indexes) internal view returns (uint256);

Parameters

NameTypeDescription
marketTypes.Market
indexesTypes.Indexes256The current indexes.

Returns

NameTypeDescription
<none>uint256The total peer-to-peer supply (total peer-to-peer supply - supply delta - idle supply).

trueP2PBorrow

Calculates the total quantity of underlyings truly borrowed peer-to-peer on the given market.

function trueP2PBorrow(Types.Market storage market, Types.Indexes256 memory indexes) internal view returns (uint256);

Parameters

NameTypeDescription
marketTypes.Market
indexesTypes.Indexes256The current indexes.

Returns

NameTypeDescription
<none>uint256The total peer-to-peer borrow (total peer-to-peer borrow - borrow delta).

repayFee

Calculates & deducts the reserve fee to repay from the given amount, updating the total peer-to-peer amount.

function repayFee(Types.Market storage market, uint256 amount, Types.Indexes256 memory indexes)
    internal
    returns (uint256);

Parameters

NameTypeDescription
marketTypes.Market
amountuint256The amount to repay (in underlying).
indexesTypes.Indexes256The current indexes.

Returns

NameTypeDescription
<none>uint256The new amount left to process (in underlying).

MarketSideDeltaLib

Git Source

Author: Morpho Labs

Library used to ease increase or decrease deltas.

Functions

increaseDelta

Given variables from a market side, updates the market side delta according to the demoted amount.

function increaseDelta(
    Types.MarketSideDelta storage delta,
    address underlying,
    uint256 amount,
    Types.MarketSideIndexes256 memory indexes,
    bool borrowSide
) internal;

Parameters

NameTypeDescription
deltaTypes.MarketSideDeltaThe market deltas to update.
underlyingaddressThe underlying address.
amountuint256The amount to supply/borrow (in underlying).
indexesTypes.MarketSideIndexes256The current indexes.
borrowSideboolWhether the market side is borrow.

decreaseDelta

Given variables from a market side, matches the delta and calculates the amount to supply/borrow from delta. Updates the market side delta accordingly.

function decreaseDelta(
    Types.MarketSideDelta storage delta,
    address underlying,
    uint256 amount,
    uint256 poolIndex,
    bool borrowSide
) internal returns (uint256, uint256);

Parameters

NameTypeDescription
deltaTypes.MarketSideDeltaThe market deltas to update.
underlyingaddressThe underlying address.
amountuint256The amount to supply/borrow (in underlying).
poolIndexuint256The current pool index.
borrowSideboolWhether the market side is borrow.

Returns

NameTypeDescription
<none>uint256The amount left to process (in underlying) and the amount to repay/withdraw (in underlying).
<none>uint256

PoolLib

Git Source

Author: Morpho Labs

Library used to ease pool interactions.

Functions

supplyToPool

Supplies amount of underlying to pool.

The pool supply index must be passed as a parameter to skip the supply on pool if it were to revert due to the amount being too small.

function supplyToPool(IPool pool, address underlying, uint256 amount, uint256 index) internal;

borrowFromPool

Borrows amount of underlyingfrom pool.

function borrowFromPool(IPool pool, address underlying, uint256 amount) internal;

repayToPool

Repays amount of underlying to pool.

If the debt has been fully repaid already, the function will return early.

function repayToPool(IPool pool, address underlying, address variableDebtToken, uint256 amount) internal;

withdrawFromPool

Withdraws amount of underlying from pool.

If the amount is greater than the balance of the aToken, the function will withdraw the maximum possible.

function withdrawFromPool(IPool pool, address underlying, address aToken, uint256 amount) internal;

getCurrentPoolIndexes

Returns the current pool indexes for underlying on the pool.

function getCurrentPoolIndexes(IPool pool, address underlying)
    internal
    view
    returns (uint256 poolSupplyIndex, uint256 poolBorrowIndex);

Returns

NameTypeDescription
poolSupplyIndexuint256The current supply index of the pool (in ray).
poolBorrowIndexuint256The current borrow index of the pool (in ray).

ReserveDataLib

Git Source

Author: Morpho Labs

Library used to ease AaveV3's reserve-related calculations.

Functions

getAccruedToTreasury

Calculates the scaled quantity of reserve dedicated to AaveV3's treasury, taking into account interests accrued.

Reference: https://github.com/aave/aave-v3-core/blob/a00f28e3ad7c0e4a369d8e06e0ac9fd0acabcab7/contracts/protocol/libraries/logic/ReserveLogic.sol#L230-L282.

function getAccruedToTreasury(DataTypes.ReserveData memory reserve, Types.Indexes256 memory indexes)
    internal
    view
    returns (uint256);

Parameters

NameTypeDescription
reserveDataTypes.ReserveDataThe reserve data of a given market.
indexesTypes.Indexes256The updated pool & peer-to-peer indexes of the associated market.

Returns

NameTypeDescription
<none>uint256The reserve's dedicated treasury, in pool unit.

Types

Git Source

Author: Morpho Labs

Library exposing all Types used in Morpho.

Structs

MarketSideDelta

Contains the market side delta data.

struct MarketSideDelta {
    uint256 scaledDelta;
    uint256 scaledP2PTotal;
}

Deltas

Contains the delta data for both supply and borrow.

struct Deltas {
    MarketSideDelta supply;
    MarketSideDelta borrow;
}

MarketSideIndexes

Contains the market side indexes.

struct MarketSideIndexes {
    uint128 poolIndex;
    uint128 p2pIndex;
}

Indexes

Contains the indexes for both supply and borrow.

struct Indexes {
    MarketSideIndexes supply;
    MarketSideIndexes borrow;
}

PauseStatuses

Contains the different pauses statuses possible in Morpho.

struct PauseStatuses {
    bool isP2PDisabled;
    bool isSupplyPaused;
    bool isSupplyCollateralPaused;
    bool isBorrowPaused;
    bool isWithdrawPaused;
    bool isWithdrawCollateralPaused;
    bool isRepayPaused;
    bool isLiquidateCollateralPaused;
    bool isLiquidateBorrowPaused;
    bool isDeprecated;
}

Market

Contains the market data that is stored in storage.

This market struct is able to be passed into memory.

struct Market {
    Indexes indexes;
    Deltas deltas;
    address underlying;
    PauseStatuses pauseStatuses;
    bool isCollateral;
    address variableDebtToken;
    uint32 lastUpdateTimestamp;
    uint16 reserveFactor;
    uint16 p2pIndexCursor;
    address aToken;
    address stableDebtToken;
    uint256 idleSupply;
}

MarketBalances

Contains storage-only dynamic arrays and mappings.

struct MarketBalances {
    LogarithmicBuckets.Buckets poolSuppliers;
    LogarithmicBuckets.Buckets p2pSuppliers;
    LogarithmicBuckets.Buckets poolBorrowers;
    LogarithmicBuckets.Buckets p2pBorrowers;
    mapping(address => uint256) collateral;
}

Iterations

Contains the minimum number of iterations for a repay or a withdraw.

struct Iterations {
    uint128 repay;
    uint128 withdraw;
}

LiquidityData

Contains the data related to the liquidity of a user.

struct LiquidityData {
    uint256 borrowable;
    uint256 maxDebt;
    uint256 debt;
}

IndexesParams

The paramaters used to compute the new peer-to-peer indexes.

struct IndexesParams {
    MarketSideIndexes256 lastSupplyIndexes;
    MarketSideIndexes256 lastBorrowIndexes;
    uint256 poolSupplyIndex;
    uint256 poolBorrowIndex;
    uint256 reserveFactor;
    uint256 p2pIndexCursor;
    Deltas deltas;
    uint256 proportionIdle;
}

GrowthFactors

Contains the data related to growth factors as part of the peer-to-peer indexes computation.

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

MarketSideIndexes256

Contains the market side indexes as uint256 instead of uint128.

struct MarketSideIndexes256 {
    uint256 poolIndex;
    uint256 p2pIndex;
}

Indexes256

Contains the indexes as uint256 instead of uint128.

struct Indexes256 {
    MarketSideIndexes256 supply;
    MarketSideIndexes256 borrow;
}

Signature

Contains the v, r and s parameters of an ECDSA signature.

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

MatchingEngineVars

Variables used in the matching engine.

struct MatchingEngineVars {
    address underlying;
    MarketSideIndexes256 indexes;
    uint256 amount;
    uint256 maxIterations;
    bool borrow;
    function (address, address, uint256, uint256, bool) returns (uint256, uint256) updateDS;
    bool demoting;
    function(uint256, uint256, MarketSideIndexes256 memory, uint256)
            pure returns (uint256, uint256, uint256) step;
}

LiquidityVars

Variables used in the liquidity computation process of a user.

Used to avoid stack too deep.

struct LiquidityVars {
    address user;
    IAaveOracle oracle;
    DataTypes.EModeCategory eModeCategory;
}

BorrowWithdrawVars

Variables used during a borrow or withdraw.

Used to avoid stack too deep.

struct BorrowWithdrawVars {
    uint256 onPool;
    uint256 inP2P;
    uint256 toWithdraw;
    uint256 toBorrow;
}

SupplyRepayVars

Variables used during a supply or repay.

Used to avoid stack too deep.

struct SupplyRepayVars {
    uint256 onPool;
    uint256 inP2P;
    uint256 toSupply;
    uint256 toRepay;
}

LiquidateVars

Variables used during a liquidate.

Used to avoid stack too deep.

struct LiquidateVars {
    uint256 closeFactor;
    uint256 seized;
}

AmountToSeizeVars

Variables used to compute the amount to seize during a liquidation.

Used to avoid stack too deep.

struct AmountToSeizeVars {
    uint256 liquidationBonus;
    uint256 borrowedTokenUnit;
    uint256 collateralTokenUnit;
    uint256 borrowedPrice;
    uint256 collateralPrice;
}

Enums

Position

Enumeration of the different position types in the protocol.

enum Position {
    POOL_SUPPLIER,
    P2P_SUPPLIER,
    POOL_BORROWER,
    P2P_BORROWER
}

MatchingEngine

Git Source

Inherits: MorphoInternal

Author: Morpho Labs

Abstract contract with functions to promote or demote users to/from peer-to-peer.

Functions

_promoteSuppliers

Promotes suppliers on the underlying market.

function _promoteSuppliers(address underlying, uint256 amount, uint256 maxIterations)
    internal
    returns (uint256, uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying market on which to promote suppliers.
amountuint256The amount of underlying to promote.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

_promoteBorrowers

Promotes borrowers on the underlying market.

function _promoteBorrowers(address underlying, uint256 amount, uint256 maxIterations)
    internal
    returns (uint256, uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying market on which to promote borrowers.
amountuint256The amount of underlying to promote.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

_demoteSuppliers

Demotes suppliers on the underlying market.

function _demoteSuppliers(address underlying, uint256 amount, uint256 maxIterations)
    internal
    returns (uint256 demoted);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying market on which to demote suppliers.
amountuint256The amount of underlying to demote.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

_demoteBorrowers

Demotes borrowers on the underlying market.

function _demoteBorrowers(address underlying, uint256 amount, uint256 maxIterations)
    internal
    returns (uint256 demoted);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying market on which to demote borrowers.
amountuint256The amount of underlying to demote.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

_promoteOrDemote

Promotes or demotes users.

function _promoteOrDemote(
    LogarithmicBuckets.Buckets storage poolBuckets,
    LogarithmicBuckets.Buckets storage p2pBuckets,
    Types.MatchingEngineVars memory vars
) internal returns (uint256 processed, uint256 iterationsDone);

Parameters

NameTypeDescription
poolBucketsLogarithmicBuckets.BucketsThe pool buckets.
p2pBucketsLogarithmicBuckets.Buckets
varsTypes.MatchingEngineVarsThe required matching engine variables to perform the matching process.

_promote

Promotes a given amount in peer-to-peer.

function _promote(uint256 poolBalance, uint256 p2pBalance, Types.MarketSideIndexes256 memory indexes, uint256 remaining)
    internal
    pure
    returns (uint256 newPoolBalance, uint256 newP2PBalance, uint256 newRemaining);

Parameters

NameTypeDescription
poolBalanceuint256The scaled balance of the user on the pool.
p2pBalanceuint256The scaled balance of the user in peer-to-peer.
indexesTypes.MarketSideIndexes256The indexes of the market.
remaininguint256The remaining amount to promote.

_demote

Demotes a given amount in peer-to-peer.

function _demote(uint256 poolBalance, uint256 p2pBalance, Types.MarketSideIndexes256 memory indexes, uint256 remaining)
    internal
    pure
    returns (uint256 newPoolBalance, uint256 newP2PBalance, uint256 newRemaining);

Parameters

NameTypeDescription
poolBalanceuint256The scaled balance of the user on the pool.
p2pBalanceuint256The scaled balance of the user in peer-to-peer.
indexesTypes.MarketSideIndexes256The indexes of the market.
remaininguint256The remaining amount to demote.

Morpho

Git Source

Inherits: IMorpho, MorphoGetters, MorphoSetters

Author: Morpho Labs

The main Morpho contract exposing all user entry points.

Functions

initialize

Initializes the contract.

function initialize(
    address addressesProvider,
    uint8 eModeCategoryId,
    address positionsManager,
    Types.Iterations memory defaultIterations
) external initializer;

Parameters

NameTypeDescription
addressesProvideraddressThe address of the pool addresses provider.
eModeCategoryIduint8The e-mode category of the deployed Morpho. 0 for the general mode.
positionsManageraddressThe address of the _positionsManager to set.
defaultIterationsTypes.IterationsThe _defaultIterations to set.

supply

Supplies amount of underlying on behalf of onBehalf. The supplied amount cannot be used as collateral but is eligible for the peer-to-peer matching.

function supply(address underlying, uint256 amount, address onBehalf, uint256 maxIterations)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to supply.
amountuint256The amount of underlying to supply.
onBehalfaddressThe address that will receive the supply position.
maxIterationsuint256The maximum number of iterations allowed during the matching process. Using 4 was shown to be efficient in Morpho Labs' simulations.

Returns

NameTypeDescription
<none>uint256The amount supplied (in underlying).

supplyWithPermit

Supplies amount of underlying of onBehalf using permit2 in a single tx. The supplied amount cannot be used as collateral but is eligible for the peer-to-peer matching.

function supplyWithPermit(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 maxIterations,
    uint256 deadline,
    Types.Signature calldata signature
) external returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to supply.
amountuint256The amount of underlying to supply.
onBehalfaddressThe address that will receive the supply position.
maxIterationsuint256The maximum number of iterations allowed during the matching process.
deadlineuint256The deadline for the permit2 signature.
signatureTypes.SignatureThe permit2 signature.

Returns

NameTypeDescription
<none>uint256The amount supplied (in underlying).

supplyCollateral

Supplies amount of underlying collateral to the pool on behalf of onBehalf. The supplied amount cannot be matched peer-to-peer but can be used as collateral.

function supplyCollateral(address underlying, uint256 amount, address onBehalf) external returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to supply.
amountuint256The amount of underlying to supply.
onBehalfaddressThe address that will receive the collateral position.

Returns

NameTypeDescription
<none>uint256The collateral amount supplied (in underlying).

supplyCollateralWithPermit

Supplies amount of underlying collateral to the pool on behalf of onBehalf using permit2 in a single tx. The supplied amount cannot be matched peer-to-peer but can be used as collateral.

function supplyCollateralWithPermit(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 deadline,
    Types.Signature calldata signature
) external returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to supply.
amountuint256The amount of underlying to supply.
onBehalfaddressThe address that will receive the collateral position.
deadlineuint256The deadline for the permit2 signature.
signatureTypes.SignatureThe permit2 signature.

Returns

NameTypeDescription
<none>uint256The collateral amount supplied (in underlying).

borrow

Borrows amount of underlying on behalf of onBehalf. If sender is not onBehalf, sender must have previously been approved by onBehalf using approveManager.

function borrow(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to borrow.
amountuint256The amount of underlying to borrow.
onBehalfaddressThe address that will receive the debt position.
receiveraddressThe address that will receive the borrowed funds.
maxIterationsuint256The maximum number of iterations allowed during the matching process. Using 4 was shown to be efficient in Morpho Labs' simulations.

Returns

NameTypeDescription
<none>uint256The amount borrowed (in underlying).

repay

Repays amount of underlying on behalf of onBehalf.

function repay(address underlying, uint256 amount, address onBehalf) external returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to borrow.
amountuint256The amount of underlying to repay.
onBehalfaddressThe address whose position will be repaid.

Returns

NameTypeDescription
<none>uint256The amount repaid (in underlying).

repayWithPermit

Repays amount of underlying on behalf of onBehalf using permit2 in a single tx.

When repaying all, one should pass type(uint160).max as amount because Permit2 does not support approvals larger than 160 bits.

function repayWithPermit(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 deadline,
    Types.Signature calldata signature
) external returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to borrow.
amountuint256The amount of underlying to repay.
onBehalfaddressThe address whose position will be repaid.
deadlineuint256The deadline for the permit2 signature.
signatureTypes.SignatureThe permit2 signature.

Returns

NameTypeDescription
<none>uint256The amount repaid (in underlying).

withdraw

Withdraws amount of underlying on behalf of onBehalf. If sender is not onBehalf, sender must have previously been approved by onBehalf using approveManager.

function withdraw(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to withdraw.
amountuint256The amount of underlying to withdraw.
onBehalfaddressThe address whose position will be withdrawn.
receiveraddressThe address that will receive the withdrawn funds.
maxIterationsuint256The maximum number of iterations allowed during the matching process. If it is less than _defaultIterations.withdraw, the latter will be used. Pass 0 to fallback to the _defaultIterations.withdraw.

Returns

NameTypeDescription
<none>uint256The amount withdrawn.

withdrawCollateral

Withdraws amount of underlying collateral on behalf of onBehalf. If sender is not onBehalf, sender must have previously been approved by onBehalf using approveManager.

function withdrawCollateral(address underlying, uint256 amount, address onBehalf, address receiver)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to withdraw.
amountuint256The amount of underlying to withdraw.
onBehalfaddressThe address whose position will be withdrawn.
receiveraddressThe address that will receive the withdrawn funds.

Returns

NameTypeDescription
<none>uint256The collateral amount withdrawn (in underlying).

liquidate

Liquidates user.

function liquidate(address underlyingBorrowed, address underlyingCollateral, address user, uint256 amount)
    external
    returns (uint256, uint256);

Parameters

NameTypeDescription
underlyingBorrowedaddressThe address of the underlying borrowed to repay.
underlyingCollateraladdressThe address of the underlying collateral to seize.
useraddressThe address of the user to liquidate.
amountuint256The amount of underlyingBorrowed to repay.

Returns

NameTypeDescription
<none>uint256The underlyingBorrowed amount repaid (in underlying) and the underlyingCollateral amount seized (in underlying).
<none>uint256

approveManager

Approves a manager to borrow/withdraw on behalf of the sender.

function approveManager(address manager, bool isAllowed) external;

Parameters

NameTypeDescription
manageraddressThe address of the manager.
isAllowedboolWhether manager is allowed to manage msg.sender's position or not.

approveManagerWithSig

Approves a manager to manage the position of msg.sender using EIP712 signature in a single tx.

function approveManagerWithSig(
    address delegator,
    address manager,
    bool isAllowed,
    uint256 nonce,
    uint256 deadline,
    Types.Signature calldata signature
) external;

Parameters

NameTypeDescription
delegatoraddressThe address of the delegator.
manageraddressThe address of the manager.
isAllowedboolWhether manager is allowed to manage msg.sender's position or not.
nonceuint256The nonce of the signed message.
deadlineuint256The deadline of the signed message.
signatureTypes.SignatureThe signature of the message.

claimRewards

Claims rewards for the given assets.

function claimRewards(address[] calldata assets, address onBehalf)
    external
    returns (address[] memory rewardTokens, uint256[] memory claimedAmounts);

Parameters

NameTypeDescription
assetsaddress[]The assets to claim rewards from (aToken or variable debt token).
onBehalfaddressThe address for which rewards are claimed and sent to.

Returns

NameTypeDescription
rewardTokensaddress[]The addresses of each reward token.
claimedAmountsuint256[]The amount of rewards claimed (in reward tokens).

_supply

function _supply(address underlying, uint256 amount, address from, address onBehalf, uint256 maxIterations)
    internal
    returns (uint256);

_supplyCollateral

function _supplyCollateral(address underlying, uint256 amount, address from, address onBehalf)
    internal
    returns (uint256);

_borrow

function _borrow(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
    internal
    returns (uint256);

_repay

function _repay(address underlying, uint256 amount, address from, address onBehalf) internal returns (uint256);

_withdraw

function _withdraw(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
    internal
    returns (uint256);

_withdrawCollateral

function _withdrawCollateral(address underlying, uint256 amount, address onBehalf, address receiver)
    internal
    returns (uint256);

_liquidate

function _liquidate(
    address underlyingBorrowed,
    address underlyingCollateral,
    uint256 amount,
    address borrower,
    address liquidator
) internal returns (uint256 repaid, uint256 seized);

MorphoGetters

Git Source

Inherits: IMorphoGetters, MorphoInternal

Author: Morpho Labs

Abstract contract exposing all accessible getters.

Functions

DOMAIN_SEPARATOR

Returns the domain separator of the EIP712.

function DOMAIN_SEPARATOR() external view returns (bytes32);

pool

Returns the pool address.

function pool() external view returns (address);

addressesProvider

Returns the addresses provider address.

function addressesProvider() external view returns (address);

eModeCategoryId

Returns the e-mode category ID of Morpho on the Aave protocol.

function eModeCategoryId() external view returns (uint256);

market

Returns the market data.

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

marketsCreated

Returns the list of the markets created.

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

scaledPoolSupplyBalance

Returns the scaled balance of user on the underlying market, supplied on pool (with underlying decimals).

function scaledPoolSupplyBalance(address underlying, address user) external view returns (uint256);

scaledP2PSupplyBalance

Returns the scaled balance of user on the underlying market, supplied peer-to-peer (with underlying decimals).

function scaledP2PSupplyBalance(address underlying, address user) external view returns (uint256);

scaledPoolBorrowBalance

Returns the scaled balance of user on the underlying market, borrowed from pool (with underlying decimals).

function scaledPoolBorrowBalance(address underlying, address user) external view returns (uint256);

scaledP2PBorrowBalance

Returns the scaled balance of user on the underlying market, borrowed peer-to-peer (with underlying decimals).

function scaledP2PBorrowBalance(address underlying, address user) external view returns (uint256);

scaledCollateralBalance

Returns the scaled balance of user on the underlying market, supplied on pool & used as collateral (with underlying decimals).

function scaledCollateralBalance(address underlying, address user) external view returns (uint256);

supplyBalance

Returns the total supply balance of user on the underlying market (in underlying).

function supplyBalance(address underlying, address user) external view returns (uint256);

borrowBalance

Returns the total borrow balance of user on the underlying market (in underlying).

function borrowBalance(address underlying, address user) external view returns (uint256);

collateralBalance

Returns the supply collateral balance of user on the underlying market (in underlying).

function collateralBalance(address underlying, address user) external view returns (uint256);

userCollaterals

Returns the list of collateral underlyings of user.

function userCollaterals(address user) external view returns (address[] memory);

userBorrows

Returns the list of borrowed underlyings of user.

function userBorrows(address user) external view returns (address[] memory);

isManagedBy

Returns whether manager is a manager of delegator.

function isManagedBy(address delegator, address manager) external view returns (bool);

userNonce

Returns the nonce of user for the manager approval signature.

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

defaultIterations

Returns the default iterations.

function defaultIterations() external view returns (Types.Iterations memory);

positionsManager

Returns the address of the positions manager.

function positionsManager() external view returns (address);

rewardsManager

Returns the address of the rewards manager.

function rewardsManager() external view returns (address);

treasuryVault

Returns the address of the treasury vault.

function treasuryVault() external view returns (address);

isClaimRewardsPaused

Returns whether the claim rewards is paused or not.

function isClaimRewardsPaused() external view returns (bool);

updatedIndexes

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

function updatedIndexes(address underlying) external view returns (Types.Indexes256 memory indexes);

liquidityData

Returns the liquidity data about the position of user.

function liquidityData(address user) external view returns (Types.LiquidityData memory);

Parameters

NameTypeDescription
useraddressThe address of the user to get the liquidity data for.

Returns

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

getNext

Returns the account after user in the same bucket of the corresponding market side.

Input address zero to get the head of the bucket.

function getNext(address underlying, Types.Position position, address user) external view returns (address);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset.
positionTypes.PositionThe position type, either pool or peer-to-peer and either supply or borrow.
useraddress

Returns

NameTypeDescription
<none>addressThe address of the next account in the data structure.

getBucketsMask

Returns the buckets mask of the corresponding market side.

function getBucketsMask(address underlying, Types.Position position) external view returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset.
positionTypes.PositionThe position type, either pool or peer-to-peer and either supply or borrow.

Returns

NameTypeDescription
<none>uint256The buckets mask of the corresponding market side.

MorphoInternal

Git Source

Inherits: MorphoStorage

Author: Morpho Labs

Abstract contract exposing Morpho's internal functions.

Functions

_domainSeparator

Dynamically computed to use the root proxy address in a delegate call.

function _domainSeparator() internal view returns (bytes32);

_createMarket

Creates a new market for the underlying token with a given reserveFactor (in bps) and a given p2pIndexCursor (in bps).

function _createMarket(address underlying, uint16 reserveFactor, uint16 p2pIndexCursor) internal;

_claimToTreasury

Claims the fee for the underlyings and send it to the _treasuryVault. Claiming on a market where there are some rewards might steal users' rewards.

function _claimToTreasury(address[] calldata underlyings, uint256[] calldata amounts) internal;

_increaseP2PDeltas

Increases the peer-to-peer delta of amount on the underlying market.

Note that this can fail if the amount is too big. In this case, consider splitting in multiple calls/txs.

function _increaseP2PDeltas(address underlying, uint256 amount) internal;

_hashEIP712TypedData

Returns the hash of the EIP712 typed data.

function _hashEIP712TypedData(bytes32 structHash) internal view returns (bytes32);

_approveManager

Approves a manager to borrow/withdraw on behalf of the delegator.

function _approveManager(address delegator, address manager, bool isAllowed) internal;

Parameters

NameTypeDescription
delegatoraddressThe address of the delegator.
manageraddressThe address of the manager.
isAllowedboolWhether manager is allowed to manage delegator's position or not.

_getUserSupplyBalanceFromIndexes

Returns the total supply balance of user on the underlying market given indexes (in underlying).

function _getUserSupplyBalanceFromIndexes(address underlying, address user, Types.Indexes256 memory indexes)
    internal
    view
    returns (uint256);

_getUserBorrowBalanceFromIndexes

Returns the total borrow balance of user on the underlying market given indexes (in underlying).

function _getUserBorrowBalanceFromIndexes(address underlying, address user, Types.Indexes256 memory indexes)
    internal
    view
    returns (uint256);

_getUserCollateralBalanceFromIndex

Returns the collateral balance of user on the underlying market a poolSupplyIndex (in underlying).

function _getUserCollateralBalanceFromIndex(address underlying, address user, uint256 poolSupplyIndex)
    internal
    view
    returns (uint256);

_getBuckets

Returns the buckets of a particular side of a market.

function _getBuckets(address underlying, Types.Position position)
    internal
    view
    returns (LogarithmicBuckets.Buckets storage);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset.
positionTypes.PositionThe side of the market.

_liquidityData

Returns the liquidity data about the position of user.

function _liquidityData(address user) internal view returns (Types.LiquidityData memory liquidityData);

Parameters

NameTypeDescription
useraddressThe address of the user to get the liquidity data for.

Returns

NameTypeDescription
liquidityDataTypes.LiquidityDataThe liquidity data of the user.

_totalCollateralData

Returns the collateral data for a given set of inputs.

The total collateral data is computed looping through all user's collateral assets.

function _totalCollateralData(Types.LiquidityVars memory vars)
    internal
    view
    returns (uint256 borrowable, uint256 maxDebt);

Parameters

NameTypeDescription
varsTypes.LiquidityVarsThe liquidity variables.

Returns

NameTypeDescription
borrowableuint256The total borrowable amount of vars.user.
maxDebtuint256The total maximum debt of vars.user.

_totalDebt

Returns the debt data for a given set of inputs.

The total debt data is computed iterating through all user's borrow assets.

function _totalDebt(Types.LiquidityVars memory vars) internal view returns (uint256 debt);

Parameters

NameTypeDescription
varsTypes.LiquidityVarsThe liquidity variables.

Returns

NameTypeDescription
debtuint256The total debt of vars.user.

_collateralData

Returns the collateral data for a given set of inputs.

function _collateralData(address underlying, Types.LiquidityVars memory vars)
    internal
    view
    returns (uint256 borrowable, uint256 maxDebt);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying collateral asset.
varsTypes.LiquidityVarsThe liquidity variables.

Returns

NameTypeDescription
borrowableuint256The borrowable amount of vars.user on the underlying market.
maxDebtuint256The maximum debt of vars.user on the underlying market.

_debt

Returns the debt value for a given set of inputs.

function _debt(address underlying, Types.LiquidityVars memory vars) internal view returns (uint256 debtValue);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to borrow.
varsTypes.LiquidityVarsThe liquidity variables.

Returns

NameTypeDescription
debtValueuint256The debt value of vars.user on the underlying market.

_assetLiquidityData

Returns the liquidity data for a given set of inputs.

function _assetLiquidityData(address underlying, Types.LiquidityVars memory vars)
    internal
    view
    returns (uint256 underlyingPrice, uint256 ltv, uint256 liquidationThreshold, uint256 underlyingUnit);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset.
varsTypes.LiquidityVarsThe liquidity variables.

Returns

NameTypeDescription
underlyingPriceuint256The price of the underlying asset (in base currency).
ltvuint256The loan to value of the underlying asset.
liquidationThresholduint256The liquidation threshold of the underlying asset.
underlyingUnituint256The token unit of the underlying asset.

_updateRewards

Prompts the rewards manager (if set) to accrue a user's rewards.

function _updateRewards(address user, address poolToken, uint256 formerOnPool) internal;

Parameters

NameTypeDescription
useraddressThe address of the user to accrue rewards for.
poolTokenaddressThe address of the pool token related to this market (aToken or variable debt token address).
formerOnPooluint256The former scaled balance on pool of the user.

_updateInDS

Updates a user's position in the data structure.

function _updateInDS(
    address poolToken,
    address user,
    LogarithmicBuckets.Buckets storage poolBuckets,
    LogarithmicBuckets.Buckets storage p2pBuckets,
    uint256 onPool,
    uint256 inP2P,
    bool demoting
) internal returns (uint256, uint256);

Parameters

NameTypeDescription
poolTokenaddressThe address of the pool token related to this market (aToken or variable debt token address).
useraddressThe address of the user to update.
poolBucketsLogarithmicBuckets.BucketsThe pool buckets.
p2pBucketsLogarithmicBuckets.BucketsThe peer-to-peer buckets.
onPooluint256The new scaled balance on pool of the user.
inP2Puint256The new scaled balance in peer-to-peer of the user.
demotingboolWhether the update is happening during a demoting process or not.

Returns

NameTypeDescription
<none>uint256The actual new scaled balance on pool and in peer-to-peer of the user after accounting for dust.
<none>uint256

_updateSupplierInDS

Updates a user's supply position in the data structure.

function _updateSupplierInDS(address underlying, address user, uint256 onPool, uint256 inP2P, bool demoting)
    internal
    returns (uint256, uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset.
useraddressThe address of the user to update.
onPooluint256The new scaled balance on pool of the user.
inP2Puint256The new scaled balance in peer-to-peer of the user.
demotingboolWhether the update is happening during a demoting process or not.

Returns

NameTypeDescription
<none>uint256The actual new scaled balance on pool and in peer-to-peer of the user after accounting for dust.
<none>uint256

_updateBorrowerInDS

Updates a user's borrow position in the data structure.

function _updateBorrowerInDS(address underlying, address user, uint256 onPool, uint256 inP2P, bool demoting)
    internal
    returns (uint256, uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset.
useraddressThe address of the user to update.
onPooluint256The new scaled balance on pool of the user.
inP2Puint256The new scaled balance in peer-to-peer of the user.
demotingboolWhether the update is happening during a demoting process or not.

Returns

NameTypeDescription
<none>uint256The actual new scaled balance on pool and in peer-to-peer of the user after accounting for dust.
<none>uint256

_setPauseStatus

Sets globally the pause status to isPaused on the underlying market.

function _setPauseStatus(address underlying, bool isPaused) internal;

_updateIndexes

Updates the indexes of the underlying market and returns them.

function _updateIndexes(address underlying) internal returns (Types.Indexes256 memory indexes);

_computeIndexes

Computes the updated indexes of the underlying market and returns them.

function _computeIndexes(address underlying) internal view returns (Types.Indexes256 memory indexes);

_getUserHealthFactor

Returns the user's health factor.

function _getUserHealthFactor(address user) internal view returns (uint256);

_assetData

Returns data relative to the given asset and its configuration, according to a given oracle.

function _assetData(
    address asset,
    IAaveOracle oracle,
    DataTypes.ReserveConfigurationMap memory config,
    address priceSource
) internal view returns (bool, uint256, uint256);

Returns

NameTypeDescription
<none>boolWhether the given asset is part of Morpho's e-mode category.
<none>uint256The asset's price or the price of the given e-mode price source if the asset is in the e-mode category, according to the given oracle.
<none>uint256The asset's unit.

_isInEModeCategory

Returns whether Morpho is in an e-mode category and the given asset configuration is in the same e-mode category.

function _isInEModeCategory(DataTypes.ReserveConfigurationMap memory config) internal view returns (bool);

MorphoSetters

Git Source

Inherits: IMorphoSetters, MorphoInternal

Author: Morpho Labs

Abstract contract exposing all setters and governance-related functions.

Functions

isMarketCreated

Prevents to update a market not created yet.

modifier isMarketCreated(address underlying);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying market.

createMarket

Creates a new market for the underlying token with a given reserveFactor (in bps) and a given p2pIndexCursor (in bps).

function createMarket(address underlying, uint16 reserveFactor, uint16 p2pIndexCursor) external onlyOwner;

claimToTreasury

Claims the fee for the underlyings and send it to the _treasuryVault.

Claiming on a market where there are some rewards might steal users' rewards.

function claimToTreasury(address[] calldata underlyings, uint256[] calldata amounts) external onlyOwner;

increaseP2PDeltas

Increases the peer-to-peer delta of amount on the underlying market.

function increaseP2PDeltas(address underlying, uint256 amount) external onlyOwner isMarketCreated(underlying);

setDefaultIterations

Sets _defaultIterations to defaultIterations.

function setDefaultIterations(Types.Iterations calldata defaultIterations) external onlyOwner;

setPositionsManager

Sets _positionsManager to positionsManager.

function setPositionsManager(address positionsManager) external onlyOwner;

setRewardsManager

Sets _rewardsManager to rewardsManager.

Note that it is possible to set the address zero. In this case, the pool rewards are not accounted.

function setRewardsManager(address rewardsManager) external onlyOwner;

setTreasuryVault

Sets _treasuryVault to treasuryVault.

Note that it is possible to set the address zero. In this case, it is not possible to claim the fee.

function setTreasuryVault(address treasuryVault) external onlyOwner;

setAssetIsCollateralOnPool

Sets the underlying asset as isCollateral on the pool.

The following invariant must hold: is collateral on Morpho => is collateral on pool.

Note that it is possible to set an asset as non-collateral even if the market is not created yet on Morpho. This is needed because an aToken with LTV = 0 can be sent to Morpho and would be set as collateral by default, thus blocking withdrawals from the pool. However, it's not possible to set an asset as collateral on pool while the market is not created on Morpho.

function setAssetIsCollateralOnPool(address underlying, bool isCollateral) external onlyOwner;

setAssetIsCollateral

Sets the underlying asset as isCollateral on Morpho.

The following invariant must hold: is collateral on Morpho => is collateral on pool.

function setAssetIsCollateral(address underlying, bool isCollateral) external onlyOwner isMarketCreated(underlying);

setReserveFactor

Sets the underlying's reserve factor to newReserveFactor (in bps).

function setReserveFactor(address underlying, uint16 newReserveFactor) external onlyOwner isMarketCreated(underlying);

setP2PIndexCursor

Sets the underlying's peer-to-peer index cursor to p2pIndexCursor (in bps).

function setP2PIndexCursor(address underlying, uint16 p2pIndexCursor) external onlyOwner isMarketCreated(underlying);

setIsClaimRewardsPaused

Sets the claim rewards pause status to isPaused.

function setIsClaimRewardsPaused(bool isPaused) external onlyOwner;

setIsSupplyPaused

Sets the supply pause status to isPaused on the underlying market.

function setIsSupplyPaused(address underlying, bool isPaused) external onlyOwner isMarketCreated(underlying);

setIsSupplyCollateralPaused

Sets the supply collateral pause status to isPaused on the underlying market.

function setIsSupplyCollateralPaused(address underlying, bool isPaused)
    external
    onlyOwner
    isMarketCreated(underlying);

setIsBorrowPaused

Sets the borrow pause status to isPaused on the underlying market.

function setIsBorrowPaused(address underlying, bool isPaused) external onlyOwner isMarketCreated(underlying);

setIsRepayPaused

Sets the repay pause status to isPaused on the underlying market.

function setIsRepayPaused(address underlying, bool isPaused) external onlyOwner isMarketCreated(underlying);

setIsWithdrawPaused

Sets the withdraw pause status to isPaused on the underlying market.

function setIsWithdrawPaused(address underlying, bool isPaused) external onlyOwner isMarketCreated(underlying);

setIsWithdrawCollateralPaused

Sets the withdraw collateral pause status to isPaused on the underlying market.

function setIsWithdrawCollateralPaused(address underlying, bool isPaused)
    external
    onlyOwner
    isMarketCreated(underlying);

setIsLiquidateCollateralPaused

Sets the liquidate collateral pause status to isPaused on the underlying market.

function setIsLiquidateCollateralPaused(address underlying, bool isPaused)
    external
    onlyOwner
    isMarketCreated(underlying);

setIsLiquidateBorrowPaused

Sets the liquidate borrow pause status to isPaused on the underlying market.

function setIsLiquidateBorrowPaused(address underlying, bool isPaused) external onlyOwner isMarketCreated(underlying);

setIsPaused

Sets globally the pause status to isPaused on the underlying market.

function setIsPaused(address underlying, bool isPaused) external onlyOwner isMarketCreated(underlying);

setIsPausedForAllMarkets

Sets the global pause status to isPaused on all markets.

function setIsPausedForAllMarkets(bool isPaused) external onlyOwner;

setIsP2PDisabled

Sets the peer-to-peer disable status to isP2PDisabled on the underlying market.

function setIsP2PDisabled(address underlying, bool isP2PDisabled) external onlyOwner isMarketCreated(underlying);

setIsDeprecated

Sets the deprecation status to isDeprecated on the underlying market.

function setIsDeprecated(address underlying, bool isDeprecated) external onlyOwner isMarketCreated(underlying);

MorphoStorage

Git Source

Inherits: Initializable, Ownable2StepUpgradeable

Author: Morpho Labs

The storage shared by Morpho's contracts.

State Variables

_pool

The address of Aave's pool.

IPool internal _pool;

_addressesProvider

The address of the pool addresses provider.

IPoolAddressesProvider internal _addressesProvider;

_eModeCategoryId

The e-mode category of the deployed Morpho.

uint8 internal _eModeCategoryId;

_marketsCreated

The list of created markets.

address[] internal _marketsCreated;

_market

The markets data.

mapping(address => Types.Market) internal _market;

_marketBalances

The markets balances data.

mapping(address => Types.MarketBalances) internal _marketBalances;

_userCollaterals

The collateral markets entered by users.

mapping(address => EnumerableSet.AddressSet) internal _userCollaterals;

_userBorrows

The borrow markets entered by users.

mapping(address => EnumerableSet.AddressSet) internal _userBorrows;

_isManagedBy

Users allowances to manage other users' accounts. delegator => manager => isManagedBy

mapping(address => mapping(address => bool)) internal _isManagedBy;

_userNonce

The nonce of users. Used to prevent replay attacks with EIP-712 signatures.

mapping(address => uint256) internal _userNonce;

_defaultIterations

The default number of iterations to use in the matching process.

Types.Iterations internal _defaultIterations;

_positionsManager

The address of the positions manager on which calls are delegated to.

address internal _positionsManager;

_rewardsManager

The address of the rewards manager to track pool rewards for users.

IRewardsManager internal _rewardsManager;

_treasuryVault

The address of the treasury vault, recipient of the reserve fee.

address internal _treasuryVault;

_isClaimRewardsPaused

Whether claiming rewards is paused or not.

bool internal _isClaimRewardsPaused;

Functions

constructor

Contract constructor.

The implementation contract disables initialization upon deployment to avoid being hijacked.

constructor();

PositionsManager

Git Source

Inherits: IPositionsManager, PositionsManagerInternal

Author: Morpho Labs

Abstract contract exposing logic functions delegate-called by the Morpho contract.

Functions

supplyLogic

Implements the supply logic.

function supplyLogic(address underlying, uint256 amount, address from, address onBehalf, uint256 maxIterations)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to supply.
amountuint256The amount of underlying to supply.
fromaddressThe address to transfer the underlying from.
onBehalfaddressThe address that will receive the supply position.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

Returns

NameTypeDescription
<none>uint256The amount supplied (in underlying).

supplyCollateralLogic

Implements the supply collateral logic.

Relies on Aave to check the supply cap when supplying collateral.

function supplyCollateralLogic(address underlying, uint256 amount, address from, address onBehalf)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to supply.
amountuint256The amount of underlying to supply.
fromaddressThe address to transfer the underlying from.
onBehalfaddressThe address that will receive the collateral position.

Returns

NameTypeDescription
<none>uint256The collateral amount supplied (in underlying).

borrowLogic

Implements the borrow logic.

function borrowLogic(address underlying, uint256 amount, address borrower, address receiver, uint256 maxIterations)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to borrow.
amountuint256The amount of underlying to borrow.
borroweraddressThe address that will receive the debt position.
receiveraddressThe address that will receive the borrowed funds.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

Returns

NameTypeDescription
<none>uint256The amount borrowed (in underlying).

repayLogic

Implements the repay logic.

function repayLogic(address underlying, uint256 amount, address repayer, address onBehalf) external returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to borrow.
amountuint256The amount of underlying to repay.
repayeraddressThe address that repays the underlying debt.
onBehalfaddressThe address whose position will be repaid.

Returns

NameTypeDescription
<none>uint256The amount repaid (in underlying).

withdrawLogic

Implements the withdraw logic.

function withdrawLogic(address underlying, uint256 amount, address supplier, address receiver, uint256 maxIterations)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to withdraw.
amountuint256The amount of underlying to withdraw.
supplieraddressThe address whose position will be withdrawn.
receiveraddressThe address that will receive the withdrawn funds.
maxIterationsuint256The maximum number of iterations allowed during the matching process.

Returns

NameTypeDescription
<none>uint256The amount withdrawn (in underlying).

withdrawCollateralLogic

Implements the withdraw collateral logic.

function withdrawCollateralLogic(address underlying, uint256 amount, address supplier, address receiver)
    external
    returns (uint256);

Parameters

NameTypeDescription
underlyingaddressThe address of the underlying asset to withdraw.
amountuint256The amount of underlying to withdraw.
supplieraddressThe address whose position will be withdrawn.
receiveraddressThe address that will receive the withdrawn funds.

Returns

NameTypeDescription
<none>uint256The collateral amount withdrawn (in underlying).

liquidateLogic

Implements the liquidation logic.

function liquidateLogic(
    address underlyingBorrowed,
    address underlyingCollateral,
    uint256 amount,
    address borrower,
    address liquidator
) external returns (uint256, uint256);

Parameters

NameTypeDescription
underlyingBorrowedaddressThe address of the underlying borrowed to repay.
underlyingCollateraladdressThe address of the underlying collateral to seize.
amountuint256The amount of underlyingBorrowed to repay.
borroweraddressThe address of the borrower to liquidate.
liquidatoraddressThe address that will liquidate the borrower.

Returns

NameTypeDescription
<none>uint256The underlyingBorrowed amount repaid (in underlying) and the underlyingCollateral amount seized (in underlying).
<none>uint256

PositionsManagerInternal

Git Source

Inherits: MatchingEngine

Author: Morpho Labs

Abstract contract defining PositionsManager's internal functions.

Functions

_validatePermission

Validates the manager's permission.

function _validatePermission(address delegator, address manager) internal view;

_validateInput

Validates the input.

function _validateInput(address underlying, uint256 amount, address user)
    internal
    view
    returns (Types.Market storage market);

_validateManagerInput

Validates the manager's permission and the input.

function _validateManagerInput(address underlying, uint256 amount, address onBehalf, address receiver)
    internal
    view
    returns (Types.Market storage market);

_validateSupply

Validates a supply action.

function _validateSupply(address underlying, uint256 amount, address user)
    internal
    view
    returns (Types.Market storage market);

_validateSupplyCollateral

Validates a supply collateral action.

function _validateSupplyCollateral(address underlying, uint256 amount, address user) internal view;

_validateBorrow

Validates a borrow action.

function _validateBorrow(address underlying, uint256 amount, address borrower, address receiver)
    internal
    view
    returns (Types.Market storage market);

_authorizeBorrow

Authorizes a borrow action.

function _authorizeBorrow(address underlying, uint256 amount, Types.Indexes256 memory indexes) internal view;

_validateRepay

Validates a repay action.

function _validateRepay(address underlying, uint256 amount, address user)
    internal
    view
    returns (Types.Market storage market);

_validateWithdraw

Validates a withdraw action.

function _validateWithdraw(address underlying, uint256 amount, address supplier, address receiver)
    internal
    view
    returns (Types.Market storage market);

_validateWithdrawCollateral

Validates a withdraw collateral action.

function _validateWithdrawCollateral(address underlying, uint256 amount, address supplier, address receiver)
    internal
    view
    returns (Types.Market storage market);

_validateLiquidate

Validates a liquidate action.

function _validateLiquidate(address underlyingBorrowed, address underlyingCollateral, address borrower) internal view;

_authorizeLiquidate

Authorizes a liquidate action.

function _authorizeLiquidate(address underlyingBorrowed, address borrower) internal view returns (uint256);

_accountSupply

Performs the accounting of a supply action.

function _accountSupply(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.SupplyRepayVars memory vars);

_accountBorrow

Performs the accounting of a borrow action. Note: the borrower's set of borrowed market is updated in _updateBorrowerInDS.

function _accountBorrow(
    address underlying,
    uint256 amount,
    address borrower,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.BorrowWithdrawVars memory vars);

_accountRepay

Performs the accounting of a repay action. Note: the borrower's set of borrowed market is updated in _updateBorrowerInDS.

function _accountRepay(
    address underlying,
    uint256 amount,
    address onBehalf,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.SupplyRepayVars memory vars);

_accountWithdraw

Performs the accounting of a withdraw action.

function _accountWithdraw(
    address underlying,
    uint256 amount,
    address supplier,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.BorrowWithdrawVars memory vars);

_accountSupplyCollateral

Performs the accounting of a supply action.

function _accountSupplyCollateral(address underlying, uint256 amount, address onBehalf, uint256 poolSupplyIndex)
    internal
    returns (uint256 collateralBalance);

_accountWithdrawCollateral

Performs the accounting of a withdraw collateral action.

function _accountWithdrawCollateral(address underlying, uint256 amount, address onBehalf, uint256 poolSupplyIndex)
    internal
    returns (uint256 collateralBalance);

_executeSupply

Executes a supply action.

function _executeSupply(
    address underlying,
    uint256 amount,
    address from,
    address onBehalf,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.SupplyRepayVars memory vars);

_executeBorrow

Executes a borrow action.

function _executeBorrow(
    address underlying,
    uint256 amount,
    address onBehalf,
    address receiver,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.BorrowWithdrawVars memory vars);

_executeRepay

Executes a repay action.

function _executeRepay(
    address underlying,
    uint256 amount,
    address repayer,
    address onBehalf,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.SupplyRepayVars memory vars);

_executeWithdraw

Executes a withdraw action.

function _executeWithdraw(
    address underlying,
    uint256 amount,
    address onBehalf,
    address receiver,
    uint256 maxIterations,
    Types.Indexes256 memory indexes
) internal returns (Types.BorrowWithdrawVars memory vars);

_executeSupplyCollateral

Executes a supply collateral action.

function _executeSupplyCollateral(
    address underlying,
    uint256 amount,
    address from,
    address onBehalf,
    uint256 poolSupplyIndex
) internal;

_executeWithdrawCollateral

Executes a withdraw collateral action.

function _executeWithdrawCollateral(
    address underlying,
    uint256 amount,
    address onBehalf,
    address receiver,
    uint256 poolSupplyIndex
) internal;

_addToPool

Given variables from a market side, calculates the amount to supply/borrow and a new on pool amount.

function _addToPool(uint256 amount, uint256 onPool, uint256 poolIndex) internal pure returns (uint256, uint256);

Parameters

NameTypeDescription
amountuint256The amount to supply/borrow.
onPooluint256The current user's scaled on pool balance.
poolIndexuint256The current pool index.

Returns

NameTypeDescription
<none>uint256The amount to supply/borrow and the new on pool amount.
<none>uint256

_subFromPool

Given variables from a market side, calculates the amount to repay/withdraw, the amount left to process, and a new on pool amount.

function _subFromPool(uint256 amount, uint256 onPool, uint256 poolIndex)
    internal
    pure
    returns (uint256, uint256, uint256);

Parameters

NameTypeDescription
amountuint256The amount to repay/withdraw.
onPooluint256The current user's scaled on pool balance.
poolIndexuint256The current pool index.

Returns

NameTypeDescription
<none>uint256The amount left to process, the amount to repay/withdraw, and the new on pool amount.
<none>uint256
<none>uint256

_promoteRoutine

Given variables from a market side, promotes users and calculates the amount to repay/withdraw from promote, the amount left to process, and the number of iterations left.

function _promoteRoutine(
    address underlying,
    uint256 amount,
    uint256 maxIterations,
    function(address, uint256, uint256) returns (uint256, uint256) promote
) internal returns (uint256, uint256, uint256);

Parameters

NameTypeDescription
underlyingaddressThe underlying address.
amountuint256The amount to supply/borrow.
maxIterationsuint256The maximum number of iterations to run.
promotefunction (address, uint256, uint256) returns (uint256, uint256)The promote function.

Returns

NameTypeDescription
<none>uint256The amount left to process, the amount to repay/withdraw from promote, and the number of iterations left.
<none>uint256
<none>uint256

_calculateAmountToSeize

Calculates the amount to seize during a liquidation process.

function _calculateAmountToSeize(
    address underlyingBorrowed,
    address underlyingCollateral,
    uint256 maxToRepay,
    address borrower,
    uint256 poolSupplyIndex
) internal view returns (uint256 amountToRepay, uint256 amountToSeize);

Parameters

NameTypeDescription
underlyingBorrowedaddressThe address of the underlying borrowed asset.
underlyingCollateraladdressThe address of the underlying collateral asset.
maxToRepayuint256The maximum amount of underlyingBorrowed to repay.
borroweraddressThe address of the borrower being liquidated.
poolSupplyIndexuint256The current pool supply index of the underlyingCollateral market.

Returns

NameTypeDescription
amountToRepayuint256The amount of underlyingBorrowed to repay.
amountToSeizeuint256The amount of underlyingCollateral to seize.

RewardsManager

Git Source

Inherits: IRewardsManager, Initializable

Author: Morpho Labs

Contract managing Aave's protocol rewards.

State Variables

_REWARDS_CONTROLLER

The address of Aave's rewards controller.

The rewards controller is, in theory, specific to an asset. In practice, it is the same for all assets and it is supposed to be true for future assets as well.

IRewardsController internal immutable _REWARDS_CONTROLLER;

_MORPHO

The address of the Morpho protocol.

IMorpho internal immutable _MORPHO;

_localAssetData

The local data related to a given asset (either aToken or debt token). asset -> reward -> RewardData

mapping(address => mapping(address => RewardData)) internal _localAssetData;

Functions

onlyMorpho

Prevents a user to call function allowed for the main Morpho contract only.

modifier onlyMorpho();

constructor

Contract constructor.

The implementation contract disables initialization upon deployment to avoid being hijacked.

constructor(address rewardsController, address morpho);

Parameters

NameTypeDescription
rewardsControlleraddressThe address of the Aave rewards controller.
morphoaddressThe address of the main Morpho contract.

claimRewards

Accrues unclaimed rewards for the given assets and returns the total unclaimed rewards.

function claimRewards(address[] calldata assets, address user)
    external
    onlyMorpho
    returns (address[] memory rewardsList, uint256[] memory claimedAmounts);

Parameters

NameTypeDescription
assetsaddress[]The assets for which to accrue rewards (aToken or variable debt token).
useraddressThe address of the user.

Returns

NameTypeDescription
rewardsListaddress[]The list of reward tokens.
claimedAmountsuint256[]The list of claimed reward amounts.

updateUserRewards

Updates the unclaimed rewards of a user.

Only called by Morpho at positions updates in the data structure.

function updateUserRewards(address user, address asset, uint256 userBalance) external onlyMorpho;

Parameters

NameTypeDescription
useraddressThe address of the user.
assetaddressThe address of the reference asset of the distribution (aToken or variable debt token).
userBalanceuint256The current user asset balance.

MORPHO

Returns the Morpho protocol address.

function MORPHO() external view returns (address);

REWARDS_CONTROLLER

Returns the rewards controller address.

function REWARDS_CONTROLLER() external view returns (address);

getRewardData

Returns the last updated index and timestamp for a specific asset and reward token.

function getRewardData(address asset, address reward)
    external
    view
    returns (uint256 startingIndex, uint256 index, uint256 lastUpdateTimestamp);

Parameters

NameTypeDescription
assetaddressThe address of the asset.
rewardaddressThe address of the reward token.

Returns

NameTypeDescription
startingIndexuint256The index from which the rewards manager begins tracking the rewards controller.
indexuint256The last updated index.
lastUpdateTimestampuint256The last updated timestamp.

getUserData

Returns the user's index and accrued rewards for a specific asset and rewards pair.

function getUserData(address asset, address reward, address user)
    external
    view
    returns (uint256 index, uint256 accrued);

Parameters

NameTypeDescription
assetaddressThe address of the asset.
rewardaddressThe address of the reward token.
useraddressThe address of the user.

Returns

NameTypeDescription
indexuint256The user's index.
accrueduint256The user's accrued rewards.

getUserAccruedRewards

Returns user's accrued rewards for the specified assets and reward token

function getUserAccruedRewards(address[] calldata assets, address user, address reward)
    external
    view
    returns (uint256 totalAccrued);

Parameters

NameTypeDescription
assetsaddress[]The list of assets to retrieve accrued rewards.
useraddressThe address of the user.
rewardaddressThe address of the reward token.

Returns

NameTypeDescription
totalAccrueduint256The total amount of accrued rewards.

getAllUserRewards

Returns user's rewards for the specified assets and for all reward tokens.

function getAllUserRewards(address[] calldata assets, address user)
    external
    view
    returns (address[] memory rewardsList, uint256[] memory unclaimedAmounts);

Parameters

NameTypeDescription
assetsaddress[]The list of assets to retrieve rewards.
useraddressThe address of the user.

Returns

NameTypeDescription
rewardsListaddress[]The list of reward tokens.
unclaimedAmountsuint256[]The list of unclaimed reward amounts.

getUserRewards

Returns user's rewards for the specified assets and reward token.

function getUserRewards(address[] calldata assets, address user, address reward) external view returns (uint256);

Parameters

NameTypeDescription
assetsaddress[]The list of assets to retrieve rewards.
useraddressThe address of the user.
rewardaddressThe address of the reward token

Returns

NameTypeDescription
<none>uint256The user's rewards in reward token.

getUserAssetIndex

Returns the user's index for the specified asset and reward token.

If an already listed AaveV3 reward token is not yet tracked (startingIndex == 0), this view function ignores that it will get updated upon interaction.

function getUserAssetIndex(address user, address asset, address reward) external view returns (uint256);

Parameters

NameTypeDescription
useraddressThe address of the user.
assetaddressThe address of the reference asset of the distribution (aToken or variable debt token).
rewardaddressThe address of the reward token.

Returns

NameTypeDescription
<none>uint256The user's index.

getAssetIndex

Returns the virtually updated asset index for the specified asset and reward token.

function getAssetIndex(address asset, address reward) external view returns (uint256 assetIndex);

Parameters

NameTypeDescription
assetaddressThe address of the reference asset of the distribution (aToken or variable debt token).
rewardaddressThe address of the reward token.

Returns

NameTypeDescription
assetIndexuint256The reward token's virtually updated asset index.

_updateRewardData

Updates the state of the distribution for the specified reward.

function _updateRewardData(
    RewardData storage localRewardData,
    address asset,
    address reward,
    uint256 scaledTotalSupply,
    uint256 assetUnit
) internal returns (uint256 newIndex, bool indexUpdated);

Parameters

NameTypeDescription
localRewardDataRewardDataThe local reward's data.
assetaddressThe asset being rewarded.
rewardaddressThe address of the reward token.
scaledTotalSupplyuint256The current scaled total supply of underlying assets for this distribution.
assetUnituint256The asset's unit (10**decimals).

Returns

NameTypeDescription
newIndexuint256The new distribution index.
indexUpdatedboolTrue if the index was updated, false otherwise.

_updateUserData

Updates the state of the distribution for the specific user.

function _updateUserData(
    RewardData storage localRewardData,
    address user,
    uint256 userBalance,
    uint256 newAssetIndex,
    uint256 assetUnit
) internal returns (uint256 rewardsAccrued, bool dataUpdated);

Parameters

NameTypeDescription
localRewardDataRewardDataThe local reward's data
useraddressThe address of the user.
userBalanceuint256The current user asset balance.
newAssetIndexuint256The new index of the asset distribution.
assetUnituint256The asset's unit (10**decimals).

Returns

NameTypeDescription
rewardsAccrueduint256The rewards accrued since the last update.
dataUpdatedboolTrue if the data was updated, false otherwise.

_updateData

Iterates and accrues all the rewards for asset of the specific user.

function _updateData(address user, address asset, uint256 userBalance, uint256 scaledTotalSupply) internal;

Parameters

NameTypeDescription
useraddressThe user address.
assetaddressThe address of the reference asset of the distribution.
userBalanceuint256The current user asset balance.
scaledTotalSupplyuint256The current scaled total supply for this distribution.

_updateDataMultiple

Accrues all the rewards of the assets specified in the userAssetBalances list.

function _updateDataMultiple(address user, UserAssetBalance[] memory userAssetBalances) internal;

Parameters

NameTypeDescription
useraddressThe address of the user.
userAssetBalancesUserAssetBalance[]The list of structs with the user balance and total supply of a set of assets.

_getUserReward

Returns the accrued unclaimed amount of a reward from a user over a list of distribution.

function _getUserReward(address user, address reward, UserAssetBalance[] memory userAssetBalances)
    internal
    view
    returns (uint256 unclaimedRewards);

Parameters

NameTypeDescription
useraddressThe address of the user.
rewardaddressThe address of the reward token.
userAssetBalancesUserAssetBalance[]List of structs with the user balance and total supply of a set of assets.

Returns

NameTypeDescription
unclaimedRewardsuint256The accrued rewards for the user until the moment.

_getPendingRewards

Computes the pending (not yet accrued) rewards since the last user action.

function _getPendingRewards(address user, address reward, UserAssetBalance memory userAssetBalance)
    internal
    view
    returns (uint256);

Parameters

NameTypeDescription
useraddressThe address of the user.
rewardaddressThe address of the reward token.
userAssetBalanceUserAssetBalanceThe struct with the user balance and total supply of the incentivized asset.

Returns

NameTypeDescription
<none>uint256The pending rewards for the user since the last user action.

_getRewards

Computes user's accrued rewards on a distribution.

function _getRewards(uint256 userBalance, uint256 reserveIndex, uint256 userIndex, uint256 assetUnit)
    internal
    pure
    returns (uint256 rewards);

Parameters

NameTypeDescription
userBalanceuint256The current user asset balance.
reserveIndexuint256The current index of the distribution.
userIndexuint256The index stored for the user, representing its staking moment.
assetUnituint256The asset's unit (10**decimals).

Returns

NameTypeDescription
rewardsuint256The rewards accrued.

_getAssetIndex

Computes the next value of an specific distribution index, with validations.

function _getAssetIndex(
    RewardData storage localRewardData,
    address asset,
    address reward,
    uint256 scaledTotalSupply,
    uint256 assetUnit
) internal view returns (uint256, uint256);

Parameters

NameTypeDescription
localRewardDataRewardDataThe local reward's data.
assetaddressThe asset being rewarded.
rewardaddressThe address of the reward token.
scaledTotalSupplyuint256The current total supply of underlying assets for this distribution.
assetUnituint256The asset's unit (10**decimals).

Returns

NameTypeDescription
<none>uint256The former index and the new index in this order.
<none>uint256

_getUserAssetBalances

Returns user balances and total supply of all the assets specified by the assets parameter.

function _getUserAssetBalances(address[] calldata assets, address user)
    internal
    view
    returns (UserAssetBalance[] memory userAssetBalances);

Parameters

NameTypeDescription
assetsaddress[]List of assets to retrieve user balance and total supply.
useraddressThe address of the user.

Returns

NameTypeDescription
userAssetBalancesUserAssetBalance[]The list of structs with user balance and total supply of the given assets.

_computeUserIndex

Computes the index of a user for a specific reward distribution.

function _computeUserIndex(RewardData storage localRewardData, address user) internal view returns (uint256);

Parameters

NameTypeDescription
localRewardDataRewardDataThe local reward's data.
useraddressThe address of the user.

Returns

NameTypeDescription
<none>uint256The index of the user for the distribution.