About Malda Protocol

Malda Protocol solves the fragmentation problem in DeFi by creating a unified lending experience across multiple EVM networks. The protocol enables users to:

  • Access lending markets across different L2s as if they were a single network
  • Unified liquidity and interest rates across all chains
  • Execute lending operations across chains without bridging or wrapping assets
  • Maintain full control of their funds in a self-custodial manner

About this repository

This repository contains the source for the onchain Solidity components required to run Malda, the first DeFi protocol built in the Risc Zero zkVM. These critical components serve multiple function within the Malda application:

  • Secure protocol ledger onchain
  • Execute UserOps leveraging proofs generated mwith the malda-zk-coprocessor component
  • Provides an entry point for users from multiple underlying chains leveraging mTokenGateway contract

Contents

Operator

Git Source

Inherits: OperatorStorage, ImTokenOperationTypes, OwnableUpgradeable

Functions

constructor

Note: oz-upgrades-unsafe-allow: constructor

constructor();

initialize

function initialize(address _rolesOperator, address _rewardDistributor, address _admin) public initializer;

onlyAllowedUser

modifier onlyAllowedUser(address user);

setWhitelistedUser

Sets user whitelist status

function setWhitelistedUser(address user, bool state) external onlyOwner;

Parameters

NameTypeDescription
useraddressThe user address
stateboolThe new staate

enableWhitelist

Enable user whitelist

function enableWhitelist() external onlyOwner;

disableWhitelist

Disable user whitelist

function disableWhitelist() external onlyOwner;

setRolesOperator

Sets a new Operator for the market

Admin function to set a new operator

function setRolesOperator(address _roles) external onlyOwner;

setPriceOracle

Sets a new price oracle

Admin function to set a new price oracle

function setPriceOracle(address newOracle) external onlyOwner;

setCloseFactor

Sets the closeFactor used when liquidating borrows

Admin function to set closeFactor

function setCloseFactor(uint256 newCloseFactorMantissa) external onlyOwner;

Parameters

NameTypeDescription
newCloseFactorMantissauint256New close factor, scaled by 1e18

setCollateralFactor

Sets the collateralFactor for a market

Admin function to set per-market collateralFactor

function setCollateralFactor(address mToken, uint256 newCollateralFactorMantissa) external onlyOwner;

Parameters

NameTypeDescription
mTokenaddressThe market to set the factor on
newCollateralFactorMantissauint256The new collateral factor, scaled by 1e18

setLiquidationIncentive

Sets liquidationIncentive

Admin function to set liquidationIncentive

function setLiquidationIncentive(address market, uint256 newLiquidationIncentiveMantissa) external onlyOwner;

Parameters

NameTypeDescription
marketaddress
newLiquidationIncentiveMantissauint256New liquidationIncentive scaled by 1e18

supportMarket

Add the market to the markets mapping and set it as listed

Admin function to set isListed and add support for the market

function supportMarket(address mToken) external onlyOwner;

Parameters

NameTypeDescription
mTokenaddressThe address of the market (token) to list

setOutflowVolumeTimeWindow

Sets outflow volume time window

function setOutflowVolumeTimeWindow(uint256 newTimeWindow) external onlyOwner;

Parameters

NameTypeDescription
newTimeWindowuint256The new reset time window

setOutflowTimeLimitInUSD

Sets outflow volume limit

when 0, it means there's no limit

function setOutflowTimeLimitInUSD(uint256 amount) external onlyOwner;

Parameters

NameTypeDescription
amountuint256The new limit

resetOutflowVolume

Resets outflow volume

function resetOutflowVolume() external onlyOwner;

checkOutflowVolumeLimit

Verifies outflow volule limit

function checkOutflowVolumeLimit(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The new limit

setMarketBorrowCaps

Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.

function setMarketBorrowCaps(address[] calldata mTokens, uint256[] calldata newBorrowCaps) external;

Parameters

NameTypeDescription
mTokensaddress[]The addresses of the markets (tokens) to change the borrow caps for
newBorrowCapsuint256[]The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.

setMarketSupplyCaps

Set the given supply caps for the given mToken markets. Supplying that brings total supply to or above supply cap will revert.

function setMarketSupplyCaps(address[] calldata mTokens, uint256[] calldata newSupplyCaps) external;

Parameters

NameTypeDescription
mTokensaddress[]The addresses of the markets (tokens) to change the supply caps for
newSupplyCapsuint256[]The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.

setPaused

Set pause for a specific operation

function setPaused(address mToken, ImTokenOperationTypes.OperationType _type, bool state) external;

Parameters

NameTypeDescription
mTokenaddressThe market token address
_typeImTokenOperationTypes.OperationTypeThe pause operation type
stateboolThe pause operation status

setRewardDistributor

Admin function to change the Reward Distributor

function setRewardDistributor(address newRewardDistributor) external onlyOwner;

Parameters

NameTypeDescription
newRewardDistributoraddressThe address of the new Reward Distributor

isOperator

Should return true

function isOperator() external pure override returns (bool);

isPaused

Returns if operation is paused

function isPaused(address mToken, ImTokenOperationTypes.OperationType _type) external view override returns (bool);

Parameters

NameTypeDescription
mTokenaddressThe mToken to check
_typeImTokenOperationTypes.OperationTypethe operation type

getAssetsIn

Returns the assets an account has entered

function getAssetsIn(address _user) external view override returns (address[] memory mTokens);

Parameters

NameTypeDescription
_useraddressThe address of the account to pull assets for

Returns

NameTypeDescription
mTokensaddress[]A dynamic list with the assets the account has entered

checkMembership

Returns whether the given account is entered in the given asset

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

Parameters

NameTypeDescription
accountaddressThe address of the account to check
mTokenaddressThe mToken to check

Returns

NameTypeDescription
<none>boolTrue if the account is in the asset, otherwise false.

getAllMarkets

A list of all markets

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

isDeprecated

Returns true if the given mToken market has been deprecated

All borrows in a deprecated mToken market can be immediately liquidated

function isDeprecated(address mToken) external view override returns (bool);

Parameters

NameTypeDescription
mTokenaddressThe market to check if deprecated

isMarketListed

Returns true/false

function isMarketListed(address mToken) external view override returns (bool);

getAccountLiquidity

Determine the current account liquidity wrt collateral requirements

function getAccountLiquidity(address account) public view returns (uint256, uint256);

Returns

NameTypeDescription
<none>uint256account liquidity in excess of collateral requirements, account shortfall below collateral requirements)
<none>uint256

getHypotheticalAccountLiquidity

Determine what the account liquidity would be if the given amounts were redeemed/borrowed

function getHypotheticalAccountLiquidity(
    address account,
    address mTokenModify,
    uint256 redeemTokens,
    uint256 borrowAmount
) external view returns (uint256, uint256);

Parameters

NameTypeDescription
accountaddressThe account to determine liquidity for
mTokenModifyaddressThe market to hypothetically redeem/borrow in
redeemTokensuint256The number of tokens to hypothetically redeem
borrowAmountuint256The amount of underlying to hypothetically borrow

Returns

NameTypeDescription
<none>uint256hypothetical account liquidity in excess of collateral requirements, hypothetical account shortfall below collateral requirements)
<none>uint256

liquidateCalculateSeizeTokens

Calculate number of tokens of collateral asset to seize given an underlying amount

Used in liquidation (called in mTokenBorrowed.liquidate)

function liquidateCalculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint256 actualRepayAmount)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
mTokenBorrowedaddressThe address of the borrowed mToken
mTokenCollateraladdressThe address of the collateral mToken
actualRepayAmountuint256The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens

Returns

NameTypeDescription
<none>uint256number of mTokenCollateral tokens to be seized in a liquidation

enterMarkets

Add assets to be included in account liquidity calculation

function enterMarkets(address[] calldata _mTokens) external override onlyAllowedUser(msg.sender);

Parameters

NameTypeDescription
_mTokensaddress[]The list of addresses of the mToken markets to be enabled

enterMarketsWithSender

Add asset (msg.sender) to be included in account liquidity calculation

function enterMarketsWithSender(address _account) external override onlyAllowedUser(_account);

Parameters

NameTypeDescription
_accountaddressThe account to add for

exitMarket

Removes asset from sender's account liquidity calculation

Sender must not have an outstanding borrow balance in the asset, or be providing necessary collateral for an outstanding borrow.

function exitMarket(address _mToken) external override;

Parameters

NameTypeDescription
_mTokenaddressThe address of the asset to be removed

claimMalda

Claim all the MALDA accrued by holder in all markets

function claimMalda(address holder) external override;

Parameters

NameTypeDescription
holderaddressThe address to claim MALDA for

claimMalda

Claim all the MALDA accrued by holder in the specified markets

function claimMalda(address holder, address[] memory mTokens) external override;

Parameters

NameTypeDescription
holderaddressThe address to claim MALDA for
mTokensaddress[]The list of markets to claim MALDA in

claimMalda

Claim all MALDA accrued by the holders

function claimMalda(address[] memory holders, address[] memory mTokens, bool borrowers, bool suppliers)
    external
    override;

Parameters

NameTypeDescription
holdersaddress[]The addresses to claim MALDA for
mTokensaddress[]The list of markets to claim MALDA in
borrowersboolWhether or not to claim MALDA earned by borrowing
suppliersboolWhether or not to claim MALDA earned by supplying

getUSDValueForAllMarkets

Returns USD value for all markets

function getUSDValueForAllMarkets() external view returns (uint256);

beforeWithdrawOnExtension

Checks whitelist status on withdrawOnExtension

function beforeWithdrawOnExtension(address user) external view onlyAllowedUser(user);

Parameters

NameTypeDescription
useraddressThe user to check

beforeBorrowOnExtension

Checks whitelist status on borrowOnExtension

function beforeBorrowOnExtension(address user) external view onlyAllowedUser(user);

Parameters

NameTypeDescription
useraddressThe user to check

beforeRebalancing

Checks if the account should be allowed to rebalance tokens

function beforeRebalancing(address mToken) external view override;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the transfer against

beforeMTokenTransfer

Checks if the account should be allowed to transfer tokens in the given market

function beforeMTokenTransfer(address mToken, address src, address dst, uint256 transferTokens) external override;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the transfer against
srcaddressThe account which sources the tokens
dstaddressThe account which receives the tokens
transferTokensuint256The number of mTokens to transfer

beforeMTokenMint

Checks if the account should be allowed to mint tokens in the given market

function beforeMTokenMint(address mToken, address minter) external override onlyAllowedUser(minter);

Parameters

NameTypeDescription
mTokenaddressThe market to verify the mint against
minteraddressThe account which would get the minted tokens

afterMTokenMint

Validates mint and reverts on rejection. May emit logs.

function afterMTokenMint(address mToken) external view override;

Parameters

NameTypeDescription
mTokenaddressAsset being minted

beforeMTokenRedeem

Checks if the account should be allowed to redeem tokens in the given market

function beforeMTokenRedeem(address mToken, address redeemer, uint256 redeemTokens)
    external
    override
    onlyAllowedUser(redeemer);

Parameters

NameTypeDescription
mTokenaddressThe market to verify the redeem against
redeemeraddressThe account which would redeem the tokens
redeemTokensuint256The number of mTokens to exchange for the underlying asset in the market

beforeMTokenBorrow

Checks if the account should be allowed to borrow the underlying asset of the given market

function beforeMTokenBorrow(address mToken, address borrower, uint256 borrowAmount)
    external
    override
    onlyAllowedUser(borrower);

Parameters

NameTypeDescription
mTokenaddressThe market to verify the borrow against
borroweraddressThe account which would borrow the asset
borrowAmountuint256The amount of underlying the account would borrow

beforeMTokenRepay

Checks if the account should be allowed to repay a borrow in the given market

function beforeMTokenRepay(address mToken, address borrower) external onlyAllowedUser(borrower);

Parameters

NameTypeDescription
mTokenaddressThe market to verify the repay against
borroweraddressThe account which would borrowed the asset

beforeMTokenLiquidate

Checks if the liquidation should be allowed to occur

function beforeMTokenLiquidate(address mTokenBorrowed, address mTokenCollateral, address borrower, uint256 repayAmount)
    external
    view
    override
    onlyAllowedUser(borrower);

Parameters

NameTypeDescription
mTokenBorrowedaddressAsset which was borrowed by the borrower
mTokenCollateraladdressAsset which was used as collateral and will be seized
borroweraddressThe address of the borrower
repayAmountuint256The amount of underlying being repaid

beforeMTokenSeize

Checks if the seizing of assets should be allowed to occur

function beforeMTokenSeize(address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower)
    external
    override;

Parameters

NameTypeDescription
mTokenCollateraladdressAsset which was used as collateral and will be seized
mTokenBorrowedaddressAsset which was borrowed by the borrower
liquidatoraddressThe address repaying the borrow and seizing the collateral
borroweraddressThe address of the borrower

_convertMarketAmountToUSDValue

function _convertMarketAmountToUSDValue(uint256 amount, address mToken) internal view returns (uint256);

_activateMarket

function _activateMarket(address _mToken, address borrower) private;

_beforeRedeem

function _beforeRedeem(address mToken, address redeemer, uint256 redeemTokens) private view;

_getHypotheticalAccountLiquidity

function _getHypotheticalAccountLiquidity(
    address account,
    address mTokenModify,
    uint256 redeemTokens,
    uint256 borrowAmount
) private view returns (uint256, uint256);

_updateMaldaSupplyIndex

Notify reward distributor for supply index update

function _updateMaldaSupplyIndex(address mToken) private;

Parameters

NameTypeDescription
mTokenaddressThe market whose supply index to update

_updateMaldaBorrowIndex

Notify reward distributor for borrow index update

function _updateMaldaBorrowIndex(address mToken) private;

Parameters

NameTypeDescription
mTokenaddressThe market whose borrow index to update

_distributeSupplierMalda

Notify reward distributor for supplier update

function _distributeSupplierMalda(address mToken, address supplier) private;

Parameters

NameTypeDescription
mTokenaddressThe market in which the supplier is interacting
supplieraddressThe address of the supplier to distribute MALDA to

_distributeBorrowerMalda

Notify reward distributor for borrower update

Borrowers will not begin to accrue until after the first interaction with the protocol.

function _distributeBorrowerMalda(address mToken, address borrower) private;

Parameters

NameTypeDescription
mTokenaddressThe market in which the borrower is interacting
borroweraddressThe address of the borrower to distribute MALDA to

_claim

function _claim(address[] memory holders, address[] memory mTokens, bool borrowers, bool suppliers) private;

_isDeprecated

function _isDeprecated(address mToken) private view returns (bool);

OperatorStorage

Git Source

Inherits: IOperator, IOperatorDefender, ExponentialNoError

State Variables

rolesOperator

Roles manager

IRoles public rolesOperator;

oracleOperator

Oracle which gives the price of any given asset

address public oracleOperator;

closeFactorMantissa

Multiplier used to calculate the maximum repayAmount when liquidating a borrow

uint256 public closeFactorMantissa;

liquidationIncentiveMantissa

Multiplier representing the discount on collateral that a liquidator receives

mapping(address => uint256) public liquidationIncentiveMantissa;

accountAssets

Per-account mapping of "assets you are in", capped by maxAssets

mapping(address => address[]) public accountAssets;

markets

Official mapping of mTokens -> Market metadata

Used e.g. to determine if a market is supported

mapping(address => IOperatorData.Market) public markets;

allMarkets

A list of all markets

address[] public allMarkets;

borrowCaps

Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.

mapping(address => uint256) public borrowCaps;

supplyCaps

Supply caps enforced by supplyAllowed for each mToken address. Defaults to zero which corresponds to unlimited supplying.

mapping(address => uint256) public supplyCaps;

rewardDistributor

Reward Distributor to markets supply and borrow (including protocol token)

address public rewardDistributor;

limitPerTimePeriod

Should return outflow limit

uint256 public limitPerTimePeriod;

cumulativeOutflowVolume

Should return outflow volume

uint256 public cumulativeOutflowVolume;

lastOutflowResetTimestamp

Should return last reset time for outflow check

uint256 public lastOutflowResetTimestamp;

outflowResetTimeWindow

Should return the outflow volume time window

uint256 public outflowResetTimeWindow;

userWhitelisted

Returns true/false for user

mapping(address => bool) public userWhitelisted;

whitelistEnabled

bool public whitelistEnabled;

_paused

mapping(address => mapping(ImTokenOperationTypes.OperationType => bool)) internal _paused;

CLOSE_FACTOR_MIN_MANTISSA

uint256 internal constant CLOSE_FACTOR_MIN_MANTISSA = 0.05e18;

CLOSE_FACTOR_MAX_MANTISSA

uint256 internal constant CLOSE_FACTOR_MAX_MANTISSA = 0.9e18;

COLLATERAL_FACTOR_MAX_MANTISSA

uint256 internal constant COLLATERAL_FACTOR_MAX_MANTISSA = 0.9e18;

Events

UserWhitelisted

Emitted when user whitelist status is changed

event UserWhitelisted(address indexed user, bool state);

WhitelistEnabled

event WhitelistEnabled();

WhitelistDisabled

event WhitelistDisabled();

ActionPaused

Emitted when pause status is changed

event ActionPaused(address indexed mToken, ImTokenOperationTypes.OperationType _type, bool state);

NewRewardDistributor

Emitted when reward distributor is changed

event NewRewardDistributor(address indexed oldRewardDistributor, address indexed newRewardDistributor);

NewBorrowCap

Emitted when borrow cap for a mToken is changed

event NewBorrowCap(address indexed mToken, uint256 newBorrowCap);

NewSupplyCap

Emitted when supply cap for a mToken is changed

event NewSupplyCap(address indexed mToken, uint256 newBorrowCap);

MarketListed

Emitted when an admin supports a market

event MarketListed(address mToken);

MarketEntered

Emitted when an account enters a market

event MarketEntered(address indexed mToken, address indexed account);

MarketExited

Emitted when an account exits a market

event MarketExited(address indexed mToken, address indexed account);

NewCloseFactor

Emitted Emitted when close factor is changed by admin

event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);

NewCollateralFactor

Emitted when a collateral factor is changed by admin

event NewCollateralFactor(
    address indexed mToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa
);

NewLiquidationIncentive

Emitted when liquidation incentive is changed by admin

event NewLiquidationIncentive(
    address market, uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa
);

NewPriceOracle

Emitted when price oracle is changed

event NewPriceOracle(address indexed oldPriceOracle, address indexed newPriceOracle);

NewRolesOperator

Event emitted when rolesOperator is changed

event NewRolesOperator(address indexed oldRoles, address indexed newRoles);

OutflowLimitUpdated

Event emitted when outflow limit is updated

event OutflowLimitUpdated(address indexed sender, uint256 oldLimit, uint256 newLimit);

OutflowTimeWindowUpdated

Event emitted when outflow reset time window is updated

event OutflowTimeWindowUpdated(uint256 oldWindow, uint256 newWindow);

OutflowVolumeReset

Event emitted when outflow volume has been reset

event OutflowVolumeReset();

Errors

Operator_Paused

error Operator_Paused();

Operator_Mismatch

error Operator_Mismatch();

Operator_OnlyAdmin

error Operator_OnlyAdmin();

Operator_EmptyPrice

error Operator_EmptyPrice();

Operator_WrongMarket

error Operator_WrongMarket();

Operator_InvalidInput

error Operator_InvalidInput();

Operator_AssetNotFound

error Operator_AssetNotFound();

Operator_RepayingTooMuch

error Operator_RepayingTooMuch();

Operator_OnlyAdminOrRole

error Operator_OnlyAdminOrRole();

Operator_MarketNotListed

error Operator_MarketNotListed();

Operator_PriceFetchFailed

error Operator_PriceFetchFailed();

Operator_SenderMustBeToken

error Operator_SenderMustBeToken();

Operator_UserNotWhitelisted

error Operator_UserNotWhitelisted();

Operator_MarketSupplyReached

error Operator_MarketSupplyReached();

Operator_RepayAmountNotValid

error Operator_RepayAmountNotValid();

Operator_MarketAlreadyListed

error Operator_MarketAlreadyListed();

Operator_OutflowVolumeReached

error Operator_OutflowVolumeReached();

Operator_InvalidRolesOperator

error Operator_InvalidRolesOperator();

Operator_InsufficientLiquidity

error Operator_InsufficientLiquidity();

Operator_MarketBorrowCapReached

error Operator_MarketBorrowCapReached();

Operator_InvalidCollateralFactor

error Operator_InvalidCollateralFactor();

Operator_InvalidRewardDistributor

error Operator_InvalidRewardDistributor();

Operator_OracleUnderlyingFetchError

error Operator_OracleUnderlyingFetchError();

Operator_Deactivate_MarketBalanceOwed

error Operator_Deactivate_MarketBalanceOwed();

Structs

AccountLiquidityLocalVars

Local vars for avoiding stack-depth limits in calculating account liquidity. Note that mTokenBalance is the number of mTokens the account owns in the market, whereas borrowBalance is the amount of underlying that the account has borrowed.

struct AccountLiquidityLocalVars {
    uint256 sumCollateral;
    uint256 sumBorrowPlusEffects;
    uint256 mTokenBalance;
    uint256 borrowBalance;
    uint256 exchangeRateMantissa;
    uint256 oraclePriceMantissa;
    Exp collateralFactor;
    Exp exchangeRate;
    Exp oraclePrice;
    Exp tokensToDenom;
}

Contents

JumpRateModelV4

Git Source

Inherits: IInterestRateModel, Ownable

Implementation of the IInterestRateModel interface for calculating interest rates

State Variables

blocksPerYear

The approximate number of blocks per year that is assumed by the interest rate model

uint256 public override blocksPerYear;

multiplierPerBlock

The multiplier of utilization rate that gives the slope of the interest rate

uint256 public override multiplierPerBlock;

baseRatePerBlock

The base interest rate which is the y-intercept when utilization rate is 0

uint256 public override baseRatePerBlock;

jumpMultiplierPerBlock

The multiplierPerBlock after hitting a specified utilization point

uint256 public override jumpMultiplierPerBlock;

kink

The utilization point at which the jump multiplier is applied

uint256 public override kink;

name

A name for user-friendliness, e.g. WBTC

string public override name;

Functions

constructor

Construct an interest rate model

constructor(
    uint256 blocksPerYear_,
    uint256 baseRatePerYear,
    uint256 multiplierPerYear,
    uint256 jumpMultiplierPerYear,
    uint256 kink_,
    address owner_,
    string memory name_
) Ownable(owner_);

Parameters

NameTypeDescription
blocksPerYear_uint256The estimated number of blocks per year
baseRatePerYearuint256The base APR, scaled by 1e18
multiplierPerYearuint256The rate increase in interest wrt utilization, scaled by 1e18
jumpMultiplierPerYearuint256The multiplier per block after utilization point
kink_uint256The utilization point where the jump multiplier applies
owner_addressThe owner of the contract
name_stringA user-friendly name for the contract

updateJumpRateModel

Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)

function updateJumpRateModel(
    uint256 baseRatePerYear,
    uint256 multiplierPerYear,
    uint256 jumpMultiplierPerYear,
    uint256 kink_
) external onlyOwner;

Parameters

NameTypeDescription
baseRatePerYearuint256The approximate target base APR, as a mantissa (scaled by 1e18)
multiplierPerYearuint256The rate of increase in interest rate wrt utilization (scaled by 1e18)
jumpMultiplierPerYearuint256The multiplierPerBlock after hitting a specified utilization point
kink_uint256The utilization point at which the jump multiplier is applied

updateBlocksPerYear

Updates the blocksPerYear in order to make interest calculations simpler

function updateBlocksPerYear(uint256 blocksPerYear_) external onlyOwner;

Parameters

NameTypeDescription
blocksPerYear_uint256The new estimated eth blocks per year.

isInterestRateModel

Should return true

function isInterestRateModel() external pure override returns (bool);

utilizationRate

Calculates the utilization rate of the market

function utilizationRate(uint256 cash, uint256 borrows, uint256 reserves) public pure override returns (uint256);

Parameters

NameTypeDescription
cashuint256The total cash in the market
borrowsuint256The total borrows in the market
reservesuint256The total reserves in the market

Returns

NameTypeDescription
<none>uint256The utilization rate as a mantissa between [0, 1e18]

getBorrowRate

Returns the current borrow rate per block for the market

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

Parameters

NameTypeDescription
cashuint256The total cash in the market
borrowsuint256The total borrows in the market
reservesuint256The total reserves in the market

Returns

NameTypeDescription
<none>uint256The current borrow rate per block, scaled by 1e18

getSupplyRate

Returns the current supply rate per block for the market

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

Parameters

NameTypeDescription
cashuint256The total cash in the market
borrowsuint256The total borrows in the market
reservesuint256The total reserves in the market
reserveFactorMantissauint256The current reserve factor for the market

Returns

NameTypeDescription
<none>uint256The current supply rate per block, scaled by 1e18

_updateJumpRateModel

Internal function to update the parameters of the interest rate model

function _updateJumpRateModel(
    uint256 baseRatePerYear,
    uint256 multiplierPerYear,
    uint256 jumpMultiplierPerYear,
    uint256 kink_
) private;

Parameters

NameTypeDescription
baseRatePerYearuint256The base APR, scaled by 1e18
multiplierPerYearuint256The rate increase wrt utilization, scaled by 1e18
jumpMultiplierPerYearuint256The multiplier per block after utilization point
kink_uint256The utilization point where the jump multiplier applies

Errors

JumpRateModelV4_MultiplierNotValid

error JumpRateModelV4_MultiplierNotValid();

Contents

Contents

Contents

IAcrossReceiverV3

Git Source

Functions

handleV3AcrossMessage

function handleV3AcrossMessage(address tokenSent, uint256 amount, address relayer, bytes memory message) external;

IAcrossSpokePoolV3

Git Source

Functions

depositV3

FUNCTIONS *

function depositV3(
    address depositor,
    address recipient,
    address inputToken,
    address outputToken,
    uint256 inputAmount,
    uint256 outputAmount,
    uint256 destinationChainId,
    address exclusiveRelayer,
    uint32 quoteTimestamp,
    uint32 fillDeadline,
    uint32 exclusivityDeadline,
    bytes calldata message
) external payable;

depositV3Now

function depositV3Now(
    address depositor,
    address recipient,
    address inputToken,
    address outputToken,
    uint256 inputAmount,
    uint256 outputAmount,
    uint256 destinationChainId,
    address exclusiveRelayer,
    uint32 fillDeadlineOffset,
    uint32 exclusivityDeadline,
    bytes calldata message
) external payable;

speedUpV3Deposit

function speedUpV3Deposit(
    address depositor,
    uint32 depositId,
    uint256 updatedOutputAmount,
    address updatedRecipient,
    bytes calldata updatedMessage,
    bytes calldata depositorSignature
) external;

fillV3Relay

function fillV3Relay(V3RelayData calldata relayData, uint256 repaymentChainId) external;

fillV3RelayWithUpdatedDeposit

function fillV3RelayWithUpdatedDeposit(
    V3RelayData calldata relayData,
    uint256 repaymentChainId,
    uint256 updatedOutputAmount,
    address updatedRecipient,
    bytes calldata updatedMessage,
    bytes calldata depositorSignature
) external;

requestV3SlowFill

function requestV3SlowFill(V3RelayData calldata relayData) external;

executeV3SlowRelayLeaf

function executeV3SlowRelayLeaf(V3SlowFill calldata slowFillLeaf, uint32 rootBundleId, bytes32[] calldata proof)
    external;

Events

V3FundsDeposited

EVENTS *

event V3FundsDeposited(
    address inputToken,
    address outputToken,
    uint256 inputAmount,
    uint256 outputAmount,
    uint256 indexed destinationChainId,
    uint32 indexed depositId,
    uint32 quoteTimestamp,
    uint32 fillDeadline,
    uint32 exclusivityDeadline,
    address indexed depositor,
    address recipient,
    address exclusiveRelayer,
    bytes message
);

RequestedSpeedUpV3Deposit

event RequestedSpeedUpV3Deposit(
    uint256 updatedOutputAmount,
    uint32 indexed depositId,
    address indexed depositor,
    address updatedRecipient,
    bytes updatedMessage,
    bytes depositorSignature
);

FilledV3Relay

event FilledV3Relay(
    address inputToken,
    address outputToken,
    uint256 inputAmount,
    uint256 outputAmount,
    uint256 repaymentChainId,
    uint256 indexed originChainId,
    uint32 indexed depositId,
    uint32 fillDeadline,
    uint32 exclusivityDeadline,
    address exclusiveRelayer,
    address indexed relayer,
    address depositor,
    address recipient,
    bytes message,
    V3RelayExecutionEventInfo relayExecutionInfo
);

RequestedV3SlowFill

event RequestedV3SlowFill(
    address inputToken,
    address outputToken,
    uint256 inputAmount,
    uint256 outputAmount,
    uint256 indexed originChainId,
    uint32 indexed depositId,
    uint32 fillDeadline,
    uint32 exclusivityDeadline,
    address exclusiveRelayer,
    address depositor,
    address recipient,
    bytes message
);

Errors

DisabledRoute

ERRORS *

error DisabledRoute();

InvalidQuoteTimestamp

error InvalidQuoteTimestamp();

InvalidFillDeadline

error InvalidFillDeadline();

InvalidExclusiveRelayer

error InvalidExclusiveRelayer();

MsgValueDoesNotMatchInputAmount

error MsgValueDoesNotMatchInputAmount();

NotExclusiveRelayer

error NotExclusiveRelayer();

NoSlowFillsInExclusivityWindow

error NoSlowFillsInExclusivityWindow();

RelayFilled

error RelayFilled();

InvalidSlowFillRequest

error InvalidSlowFillRequest();

ExpiredFillDeadline

error ExpiredFillDeadline();

InvalidMerkleProof

error InvalidMerkleProof();

InvalidChainId

error InvalidChainId();

InvalidMerkleLeaf

error InvalidMerkleLeaf();

ClaimedMerkleLeaf

error ClaimedMerkleLeaf();

InvalidPayoutAdjustmentPct

error InvalidPayoutAdjustmentPct();

WrongERC7683OrderId

error WrongERC7683OrderId();

LowLevelCallFailed

error LowLevelCallFailed(bytes data);

Structs

V3RelayData

STRUCTS *

struct V3RelayData {
    address depositor;
    address recipient;
    address exclusiveRelayer;
    address inputToken;
    address outputToken;
    uint256 inputAmount;
    uint256 outputAmount;
    uint256 originChainId;
    uint32 depositId;
    uint32 fillDeadline;
    uint32 exclusivityDeadline;
    bytes message;
}

V3SlowFill

struct V3SlowFill {
    V3RelayData relayData;
    uint256 chainId;
    uint256 updatedOutputAmount;
}

V3RelayExecutionParams

struct V3RelayExecutionParams {
    V3RelayData relay;
    bytes32 relayHash;
    uint256 updatedOutputAmount;
    address updatedRecipient;
    bytes updatedMessage;
    uint256 repaymentChainId;
}

V3RelayExecutionEventInfo

struct V3RelayExecutionEventInfo {
    address updatedRecipient;
    bytes updatedMessage;
    uint256 updatedOutputAmount;
    FillType fillType;
}

Enums

FillStatus

ENUMS *

enum FillStatus {
    Unfilled,
    RequestedSlowFill,
    Filled
}

FillType

enum FillType {
    FastFill,
    ReplacedSlowFill,
    SlowFill
}

Contents

IAggregatorV3

Git Source

Functions

decimals

function decimals() external view returns (uint8);

latestRoundData

function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

Contents

IConnext

Git Source

Functions

xcall

function xcall(
    uint32 _destination,
    address _to,
    address _asset,
    address _delegate,
    uint256 _amount,
    uint256 _slippage,
    bytes calldata _callData
) external payable returns (bytes32);

xcall

function xcall(
    uint32 _destination,
    address _to,
    address _asset,
    address _delegate,
    uint256 _amount,
    uint256 _slippage,
    bytes calldata _callData,
    uint256 _relayerFee
) external returns (bytes32);

xcallIntoLocal

function xcallIntoLocal(
    uint32 _destination,
    address _to,
    address _asset,
    address _delegate,
    uint256 _amount,
    uint256 _slippage,
    bytes calldata _callData
) external payable returns (bytes32);

domain

function domain() external view returns (uint256);

Contents

IEverclearSpoke

Git Source

Functions

newIntent

Creates a new intent

function newIntent(
    uint32[] memory _destinations,
    address _receiver,
    address _inputAsset,
    address _outputAsset,
    uint256 _amount,
    uint24 _maxFee,
    uint48 _ttl,
    bytes calldata _data
) external returns (bytes32 _intentId, Intent memory _intent);

Parameters

NameTypeDescription
_destinationsuint32[]The possible destination chains of the intent
_receiveraddressThe destinantion address of the intent
_inputAssetaddressThe asset address on origin
_outputAssetaddressThe asset address on destination
_amountuint256The amount of the asset
_maxFeeuint24The maximum fee that can be taken by solvers
_ttluint48The time to live of the intent
_databytesThe data of the intent

Returns

NameTypeDescription
_intentIdbytes32The ID of the intent
_intentIntentThe intent object

Structs

Intent

struct Intent {
    uint256 val;
}

Contents

Contents

MessagingParams

Git Source

struct MessagingParams {
    uint32 dstEid;
    bytes32 receiver;
    bytes message;
    bytes options;
    bool payInLzToken;
}

MessagingReceipt

Git Source

struct MessagingReceipt {
    bytes32 guid;
    uint64 nonce;
    MessagingFee fee;
}

MessagingFee

Git Source

struct MessagingFee {
    uint256 nativeFee;
    uint256 lzTokenFee;
}

Origin

Git Source

struct Origin {
    uint32 srcEid;
    bytes32 sender;
    uint64 nonce;
}

ILayerZeroEndpointV2

Git Source

Inherits: IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext

Functions

quote

function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);

send

function send(MessagingParams calldata _params, address _refundAddress)
    external
    payable
    returns (MessagingReceipt memory);

verify

function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;

verifiable

function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);

initializable

function initializable(Origin calldata _origin, address _receiver) external view returns (bool);

lzReceive

function lzReceive(
    Origin calldata _origin,
    address _receiver,
    bytes32 _guid,
    bytes calldata _message,
    bytes calldata _extraData
) external payable;

clear

function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;

setLzToken

function setLzToken(address _lzToken) external;

lzToken

function lzToken() external view returns (address);

nativeToken

function nativeToken() external view returns (address);

setDelegate

function setDelegate(address _delegate) external;

Events

PacketSent

event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);

PacketVerified

event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);

PacketDelivered

event PacketDelivered(Origin origin, address receiver);

LzReceiveAlert

event LzReceiveAlert(
    address indexed receiver,
    address indexed executor,
    Origin origin,
    bytes32 guid,
    uint256 gas,
    uint256 value,
    bytes message,
    bytes extraData,
    bytes reason
);

LzTokenSet

event LzTokenSet(address token);

DelegateSet

event DelegateSet(address sender, address delegate);

SendParam

Git Source

Struct representing token parameters for the OFT send() operation.

struct SendParam {
    uint32 dstEid;
    bytes32 to;
    uint256 amountLD;
    uint256 minAmountLD;
    bytes extraOptions;
    bytes composeMsg;
    bytes oftCmd;
}

OFTLimit

Git Source

Struct representing OFT limit information.

These amounts can change dynamically and are up the the specific oft implementation.

struct OFTLimit {
    uint256 minAmountLD;
    uint256 maxAmountLD;
}

OFTReceipt

Git Source

Struct representing OFT receipt information.

struct OFTReceipt {
    uint256 amountSentLD;
    uint256 amountReceivedLD;
}

OFTFeeDetail

Git Source

Struct representing OFT fee details.

Future proof mechanism to provide a standardized way to communicate fees to things like a UI.

struct OFTFeeDetail {
    int256 feeAmountLD;
    string description;
}

ILayerZeroOFT

Git Source

Interface for the OftChain (OFT) token.

Does not inherit ERC20 to accommodate usage by OFTAdapter as well.

This specific interface ID is '0x02e49c2c'.

Functions

oftVersion

Retrieves interfaceID and the version of the OFT.

interfaceId: This specific interface ID is '0x02e49c2c'.

version: Indicates a cross-chain compatible msg encoding with other OFTs.

If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented. ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)

function oftVersion() external view returns (bytes4 interfaceId, uint64 version);

Returns

NameTypeDescription
interfaceIdbytes4The interface ID.
versionuint64The version.

token

Retrieves the address of the token associated with the OFT.

function token() external view returns (address);

Returns

NameTypeDescription
<none>addresstoken The address of the ERC20 token implementation.

approvalRequired

Indicates whether the OFT contract requires approval of the 'token()' to send.

Allows things like wallet implementers to determine integration requirements, without understanding the underlying token implementation.

function approvalRequired() external view returns (bool);

Returns

NameTypeDescription
<none>boolrequiresApproval Needs approval of the underlying token implementation.

sharedDecimals

Retrieves the shared decimals of the OFT.

function sharedDecimals() external view returns (uint8);

Returns

NameTypeDescription
<none>uint8sharedDecimals The shared decimals of the OFT.

quoteOFT

Provides a quote for OFT-related operations.

function quoteOFT(SendParam calldata _sendParam)
    external
    view
    returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);

Parameters

NameTypeDescription
_sendParamSendParamThe parameters for the send operation.

Returns

NameTypeDescription
<none>OFTLimitlimit The OFT limit information.
oftFeeDetailsOFTFeeDetail[]The details of OFT fees.
<none>OFTReceiptreceipt The OFT receipt information.

quoteSend

Provides a quote for the send() operation.

*MessagingFee: LayerZero msg fee

  • nativeFee: The native fee.
  • lzTokenFee: The lzToken fee.*
function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);

Parameters

NameTypeDescription
_sendParamSendParamThe parameters for the send() operation.
_payInLzTokenboolFlag indicating whether the caller is paying in the LZ token.

Returns

NameTypeDescription
<none>MessagingFeefee The calculated LayerZero messaging fee from the send() operation.

send

Executes the send() operation.

*MessagingReceipt: LayerZero msg receipt

  • guid: The unique identifier for the sent message.
  • nonce: The nonce of the sent message.
  • fee: The LayerZero fee incurred for the message.*
function send(SendParam calldata _sendParam, MessagingFee calldata _fee, address _refundAddress)
    external
    payable
    returns (MessagingReceipt memory, OFTReceipt memory);

Parameters

NameTypeDescription
_sendParamSendParamThe parameters for the send operation.
_feeMessagingFeeThe fee information supplied by the caller. - nativeFee: The native fee. - lzTokenFee: The lzToken fee.
_refundAddressaddressThe address to receive any excess funds from fees etc. on the src.

Returns

NameTypeDescription
<none>MessagingReceiptreceipt The LayerZero messaging receipt from the send() operation.
<none>OFTReceiptoftReceipt The OFT receipt information.

Events

OFTSent

event OFTSent(
    bytes32 indexed guid, uint32 dstEid, address indexed fromAddress, uint256 amountSentLD, uint256 amountReceivedLD
);

OFTReceived

event OFTReceived(bytes32 indexed guid, uint32 srcEid, address indexed toAddress, uint256 amountReceivedLD);

Errors

InvalidLocalDecimals

error InvalidLocalDecimals();

SlippageExceeded

error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);

ILayerZeroReceiverV2

Git Source

Functions

allowInitializePath

function allowInitializePath(Origin calldata _origin) external view returns (bool);

nextNonce

function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);

lzReceive

function lzReceive(
    Origin calldata _origin,
    bytes32 _guid,
    bytes calldata _message,
    address _executor,
    bytes calldata _extraData
) external payable;

MessageLibType

Git Source

enum MessageLibType {
    Send,
    Receive,
    SendAndReceive
}

IMessageLib

Git Source

Inherits: IERC165

Functions

setConfig

function setConfig(address _oapp, SetConfigParam[] calldata _config) external;

getConfig

function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);

isSupportedEid

function isSupportedEid(uint32 _eid) external view returns (bool);

version

function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);

messageLibType

function messageLibType() external view returns (MessageLibType);

SetConfigParam

Git Source

struct SetConfigParam {
    uint32 eid;
    uint32 configType;
    bytes config;
}

IMessageLibManager

Git Source

Functions

registerLibrary

function registerLibrary(address _lib) external;

isRegisteredLibrary

function isRegisteredLibrary(address _lib) external view returns (bool);

getRegisteredLibraries

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

setDefaultSendLibrary

function setDefaultSendLibrary(uint32 _eid, address _newLib) external;

defaultSendLibrary

function defaultSendLibrary(uint32 _eid) external view returns (address);

setDefaultReceiveLibrary

function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;

defaultReceiveLibrary

function defaultReceiveLibrary(uint32 _eid) external view returns (address);

setDefaultReceiveLibraryTimeout

function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;

defaultReceiveLibraryTimeout

function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);

isSupportedEid

function isSupportedEid(uint32 _eid) external view returns (bool);

isValidReceiveLibrary

function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);

setSendLibrary

------------------- OApp interfaces -------------------

function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;

getSendLibrary

function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);

isDefaultSendLibrary

function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);

setReceiveLibrary

function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;

getReceiveLibrary

function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);

setReceiveLibraryTimeout

function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;

receiveLibraryTimeout

function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);

setConfig

function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;

getConfig

function getConfig(address _oapp, address _lib, uint32 _eid, uint32 _configType)
    external
    view
    returns (bytes memory config);

Events

LibraryRegistered

event LibraryRegistered(address newLib);

DefaultSendLibrarySet

event DefaultSendLibrarySet(uint32 eid, address newLib);

DefaultReceiveLibrarySet

event DefaultReceiveLibrarySet(uint32 eid, address newLib);

DefaultReceiveLibraryTimeoutSet

event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);

SendLibrarySet

event SendLibrarySet(address sender, uint32 eid, address newLib);

ReceiveLibrarySet

event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);

ReceiveLibraryTimeoutSet

event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);

Structs

Timeout

struct Timeout {
    address lib;
    uint256 expiry;
}

IMessagingChannel

Git Source

Functions

eid

function eid() external view returns (uint32);

skip

function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;

nilify

function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;

burn

function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;

nextGuid

function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);

inboundNonce

function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);

outboundNonce

function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);

inboundPayloadHash

function inboundPayloadHash(address _receiver, uint32 _srcEid, bytes32 _sender, uint64 _nonce)
    external
    view
    returns (bytes32);

lazyInboundNonce

function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);

Events

InboundNonceSkipped

event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);

PacketNilified

event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);

PacketBurnt

event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);

IMessagingComposer

Git Source

Functions

composeQueue

function composeQueue(address _from, address _to, bytes32 _guid, uint16 _index)
    external
    view
    returns (bytes32 messageHash);

sendCompose

function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;

lzCompose

function lzCompose(
    address _from,
    address _to,
    bytes32 _guid,
    uint16 _index,
    bytes calldata _message,
    bytes calldata _extraData
) external payable;

Events

ComposeSent

event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);

ComposeDelivered

event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);

LzComposeAlert

event LzComposeAlert(
    address indexed from,
    address indexed to,
    address indexed executor,
    bytes32 guid,
    uint16 index,
    uint256 gas,
    uint256 value,
    bytes message,
    bytes extraData,
    bytes reason
);

IMessagingContext

Git Source

Functions

isSendingMessage

function isSendingMessage() external view returns (bool);

getSendContext

function getSendContext() external view returns (uint32 dstEid, address sender);

ILayerZeroEndpoint

Git Source

Inherits: ILayerZeroUserApplicationConfig

is imported from (https://github.com/LayerZero-Labs/LayerZero/blob/main/contracts/interfaces/ILayerZeroEndpoint.sol)

Functions

send

function send(
    uint16 dstChainId_,
    bytes calldata destination_,
    bytes calldata payload_,
    address payable refundAddress_,
    address zroPaymentAddress_,
    bytes calldata adapterParams_
) external payable;

receivePayload

function receivePayload(
    uint16 srcChainId_,
    bytes calldata srcAddress_,
    address dstAddress_,
    uint64 nonce_,
    uint256 gasLimit_,
    bytes calldata payload_
) external;

getInboundNonce

function getInboundNonce(uint16 srcChainId_, bytes calldata srcAddress_) external view returns (uint64);

getOutboundNonce

function getOutboundNonce(uint16 dstChainId_, address srcAddress_) external view returns (uint64);

estimateFees

function estimateFees(
    uint16 dstChainId_,
    address userApplication_,
    bytes calldata payload_,
    bool _payInZRO,
    bytes calldata _adapterParam
) external view returns (uint256 nativeFee, uint256 zroFee);

getChainId

function getChainId() external view returns (uint16);

retryPayload

function retryPayload(uint16 srcChainId_, bytes calldata srcAddress_, bytes calldata payload_) external;

hasStoredPayload

function hasStoredPayload(uint16 srcChainId_, bytes calldata srcAddress_) external view returns (bool);

getSendLibraryAddress

function getSendLibraryAddress(address userApplication_) external view returns (address);

getReceiveLibraryAddress

function getReceiveLibraryAddress(address userApplication_) external view returns (address);

isSendingPayload

function isSendingPayload() external view returns (bool);

isReceivingPayload

function isReceivingPayload() external view returns (bool);

getConfig

function getConfig(uint16 version_, uint16 chainId_, address userApplication_, uint256 configType_)
    external
    view
    returns (bytes memory);

getSendVersion

function getSendVersion(address userApplication_) external view returns (uint16);

getReceiveVersion

function getReceiveVersion(address userApplication_) external view returns (uint16);

ILayerZeroReceiver

Git Source

is imported from (https://github.com/LayerZero-Labs/LayerZero/blob/main/contracts/interfaces/ILayerZeroReceiver.sol)

Functions

lzReceive

function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;

ILayerZeroUserApplicationConfig

Git Source

is imported from (https://github.com/LayerZero-Labs/LayerZero/blob/main/contracts/interfaces/ILayerZeroUserApplicationConfig.sol)

Functions

setConfig

function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;

setSendVersion

function setSendVersion(uint16 _version) external;

setReceiveVersion

function setReceiveVersion(uint16 _version) external;

forceResumeReceive

function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;

Contents

IPohVerifier

Git Source

Functions

verify

Check if the provided signature has been signed by signer

human is supposed to be a POH address, this is what is being signed by the POH API

function verify(bytes memory signature, address human) external view returns (bool);

Parameters

NameTypeDescription
signaturebytesThe signature to check
humanaddressthe address for which the signature has been crafted

Returns

NameTypeDescription
<none>boolTrue if the signature was made by signer, false otherwise

getSigner

Returns the signer's address

function getSigner() external view returns (address);

IBridge

Git Source

Functions

getFee

computes fee for bridge operation

function getFee(uint32 _dstChainId, bytes memory _message, bytes memory _bridgeData) external view returns (uint256);

Parameters

NameTypeDescription
_dstChainIduint32destination chain id
_messagebytesoperation message data
_bridgeDatabytesspecific bridge data

sendMsg

rebalance through bridge

function sendMsg(
    uint256 _extractedAmount,
    address _market,
    uint32 _dstChainId,
    address _token,
    bytes memory _message,
    bytes memory _bridgeData
) external payable;

Parameters

NameTypeDescription
_extractedAmountuint256extracted amount for rebalancing
_marketaddressdestination address
_dstChainIduint32destination chain id
_tokenaddressthe token to rebalance
_messagebytesoperation message data
_bridgeDatabytesspecific bridge datas

IDefaultAdapter

Git Source

Functions

decimals

function decimals() external view returns (uint8);

latestRoundData

function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

latestAnswer

function latestAnswer() external view returns (int256);

latestTimestamp

function latestTimestamp() external view returns (uint256);

Structs

PriceConfig

struct PriceConfig {
    address defaultFeed;
    string toSymbol;
    uint256 underlyingDecimals;
}

IInterestRateModel

Git Source

Interface for the interest rate contracts

Functions

isInterestRateModel

Should return true

function isInterestRateModel() external view returns (bool);

blocksPerYear

The approximate number of blocks per year that is assumed by the interest rate model

function blocksPerYear() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The number of blocks per year

multiplierPerBlock

The multiplier of utilization rate that gives the slope of the interest rate

function multiplierPerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The multiplier per block

baseRatePerBlock

The base interest rate which is the y-intercept when utilization rate is 0

function baseRatePerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The base rate per block

jumpMultiplierPerBlock

The multiplierPerBlock after hitting a specified utilization point

function jumpMultiplierPerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The jump multiplier per block

kink

The utilization point at which the jump multiplier is applied

function kink() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The utilization point (kink)

name

A name for user-friendliness, e.g. WBTC

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

Returns

NameTypeDescription
<none>stringThe name of the interest rate model

utilizationRate

Calculates the utilization rate of the market

function utilizationRate(uint256 cash, uint256 borrows, uint256 reserves) external pure returns (uint256);

Parameters

NameTypeDescription
cashuint256The total cash in the market
borrowsuint256The total borrows in the market
reservesuint256The total reserves in the market

Returns

NameTypeDescription
<none>uint256The utilization rate as a mantissa between [0, 1e18]

getBorrowRate

Returns the current borrow rate per block for the market

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

Parameters

NameTypeDescription
cashuint256The total cash in the market
borrowsuint256The total borrows in the market
reservesuint256The total reserves in the market

Returns

NameTypeDescription
<none>uint256The current borrow rate per block, scaled by 1e18

getSupplyRate

Returns the current supply rate per block for the market

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

Parameters

NameTypeDescription
cashuint256The total cash in the market
borrowsuint256The total borrows in the market
reservesuint256The total reserves in the market
reserveFactorMantissauint256The current reserve factor for the market

Returns

NameTypeDescription
<none>uint256The current supply rate per block, scaled by 1e18

Events

NewInterestParams

Emitted when interest rate parameters are updated

event NewInterestParams(
    uint256 baseRatePerBlock, uint256 multiplierPerBlock, uint256 jumpMultiplierPerBlock, uint256 kink
);

Parameters

NameTypeDescription
baseRatePerBlockuint256The base rate per block
multiplierPerBlockuint256The multiplier per block for the interest rate slope
jumpMultiplierPerBlockuint256The multiplier after hitting the kink
kinkuint256The utilization point where the jump multiplier is applied

IOperatorData

Git Source

Structs

Market

struct Market {
    bool isListed;
    uint256 collateralFactorMantissa;
    mapping(address => bool) accountMembership;
    bool isMalded;
}

IOperatorDefender

Git Source

Functions

beforeRebalancing

Checks if the account should be allowed to rebalance tokens

function beforeRebalancing(address mToken) external;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the transfer against

beforeMTokenTransfer

Checks if the account should be allowed to transfer tokens in the given market

function beforeMTokenTransfer(address mToken, address src, address dst, uint256 transferTokens) external;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the transfer against
srcaddressThe account which sources the tokens
dstaddressThe account which receives the tokens
transferTokensuint256The number of mTokens to transfer

beforeMTokenMint

Checks if the account should be allowed to mint tokens in the given market

function beforeMTokenMint(address mToken, address minter) external;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the mint against
minteraddressThe account which would get the minted tokens

afterMTokenMint

Validates mint and reverts on rejection. May emit logs.

function afterMTokenMint(address mToken) external view;

Parameters

NameTypeDescription
mTokenaddressAsset being minted

beforeMTokenRedeem

Checks if the account should be allowed to redeem tokens in the given market

function beforeMTokenRedeem(address mToken, address redeemer, uint256 redeemTokens) external;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the redeem against
redeemeraddressThe account which would redeem the tokens
redeemTokensuint256The number of mTokens to exchange for the underlying asset in the market

beforeMTokenBorrow

Checks if the account should be allowed to borrow the underlying asset of the given market

function beforeMTokenBorrow(address mToken, address borrower, uint256 borrowAmount) external;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the borrow against
borroweraddressThe account which would borrow the asset
borrowAmountuint256The amount of underlying the account would borrow

beforeMTokenRepay

Checks if the account should be allowed to repay a borrow in the given market

function beforeMTokenRepay(address mToken, address borrower) external;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the repay against
borroweraddressThe account which would borrowed the asset

beforeMTokenLiquidate

Checks if the liquidation should be allowed to occur

function beforeMTokenLiquidate(address mTokenBorrowed, address mTokenCollateral, address borrower, uint256 repayAmount)
    external
    view;

Parameters

NameTypeDescription
mTokenBorrowedaddressAsset which was borrowed by the borrower
mTokenCollateraladdressAsset which was used as collateral and will be seized
borroweraddressThe address of the borrower
repayAmountuint256The amount of underlying being repaid

beforeMTokenSeize

Checks if the seizing of assets should be allowed to occur

function beforeMTokenSeize(address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower)
    external;

Parameters

NameTypeDescription
mTokenCollateraladdressAsset which was used as collateral and will be seized
mTokenBorrowedaddressAsset which was borrowed by the borrower
liquidatoraddressThe address repaying the borrow and seizing the collateral
borroweraddressThe address of the borrower

checkOutflowVolumeLimit

Checks if new used amount is within the limits of the outflow volume limit

Sender must be a listed market

function checkOutflowVolumeLimit(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256New amount

beforeWithdrawOnExtension

Checks whitelist status on withdrawOnExtension

function beforeWithdrawOnExtension(address user) external view;

Parameters

NameTypeDescription
useraddressThe user to check

beforeBorrowOnExtension

Checks whitelist status on borrowOnExtension

function beforeBorrowOnExtension(address user) external view;

Parameters

NameTypeDescription
useraddressThe user to check

IOperator

Git Source

Functions

userWhitelisted

Returns true/false for user

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

isOperator

Should return true

function isOperator() external view returns (bool);

limitPerTimePeriod

Should return outflow limit

function limitPerTimePeriod() external view returns (uint256);

cumulativeOutflowVolume

Should return outflow volume

function cumulativeOutflowVolume() external view returns (uint256);

lastOutflowResetTimestamp

Should return last reset time for outflow check

function lastOutflowResetTimestamp() external view returns (uint256);

outflowResetTimeWindow

Should return the outflow volume time window

function outflowResetTimeWindow() external view returns (uint256);

isPaused

Returns if operation is paused

function isPaused(address mToken, ImTokenOperationTypes.OperationType _type) external view returns (bool);

Parameters

NameTypeDescription
mTokenaddressThe mToken to check
_typeImTokenOperationTypes.OperationTypethe operation type

rolesOperator

Roles manager

function rolesOperator() external view returns (IRoles);

oracleOperator

Oracle which gives the price of any given asset

function oracleOperator() external view returns (address);

closeFactorMantissa

Multiplier used to calculate the maximum repayAmount when liquidating a borrow

function closeFactorMantissa() external view returns (uint256);

liquidationIncentiveMantissa

Multiplier representing the discount on collateral that a liquidator receives

function liquidationIncentiveMantissa(address market) external view returns (uint256);

isMarketListed

Returns true/false

function isMarketListed(address market) external view returns (bool);

getAssetsIn

Returns the assets an account has entered

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

Parameters

NameTypeDescription
_useraddressThe address of the account to pull assets for

Returns

NameTypeDescription
mTokensaddress[]A dynamic list with the assets the account has entered

getAllMarkets

A list of all markets

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

borrowCaps

Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.

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

supplyCaps

Supply caps enforced by supplyAllowed for each mToken address. Defaults to zero which corresponds to unlimited supplying.

function supplyCaps(address _mToken) external view returns (uint256);

rewardDistributor

Reward Distributor to markets supply and borrow (including protocol token)

function rewardDistributor() external view returns (address);

checkMembership

Returns whether the given account is entered in the given asset

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

Parameters

NameTypeDescription
accountaddressThe address of the account to check
mTokenaddressThe mToken to check

Returns

NameTypeDescription
<none>boolTrue if the account is in the asset, otherwise false.

getAccountLiquidity

Determine the current account liquidity wrt collateral requirements

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

Returns

NameTypeDescription
<none>uint256account liquidity in excess of collateral requirements, account shortfall below collateral requirements)
<none>uint256

getHypotheticalAccountLiquidity

Determine what the account liquidity would be if the given amounts were redeemed/borrowed

function getHypotheticalAccountLiquidity(
    address account,
    address mTokenModify,
    uint256 redeemTokens,
    uint256 borrowAmount
) external view returns (uint256, uint256);

Parameters

NameTypeDescription
accountaddressThe account to determine liquidity for
mTokenModifyaddressThe market to hypothetically redeem/borrow in
redeemTokensuint256The number of tokens to hypothetically redeem
borrowAmountuint256The amount of underlying to hypothetically borrow

Returns

NameTypeDescription
<none>uint256hypothetical account liquidity in excess of collateral requirements, hypothetical account shortfall below collateral requirements)
<none>uint256

getUSDValueForAllMarkets

Returns USD value for all markets

function getUSDValueForAllMarkets() external view returns (uint256);

liquidateCalculateSeizeTokens

Calculate number of tokens of collateral asset to seize given an underlying amount

Used in liquidation (called in mTokenBorrowed.liquidate)

function liquidateCalculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint256 actualRepayAmount)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
mTokenBorrowedaddressThe address of the borrowed mToken
mTokenCollateraladdressThe address of the collateral mToken
actualRepayAmountuint256The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens

Returns

NameTypeDescription
<none>uint256number of mTokenCollateral tokens to be seized in a liquidation

isDeprecated

Returns true if the given mToken market has been deprecated

All borrows in a deprecated mToken market can be immediately liquidated

function isDeprecated(address mToken) external view returns (bool);

Parameters

NameTypeDescription
mTokenaddressThe market to check if deprecated

setPaused

Set pause for a specific operation

function setPaused(address mToken, ImTokenOperationTypes.OperationType _type, bool state) external;

Parameters

NameTypeDescription
mTokenaddressThe market token address
_typeImTokenOperationTypes.OperationTypeThe pause operation type
stateboolThe pause operation status

enterMarkets

Add assets to be included in account liquidity calculation

function enterMarkets(address[] calldata _mTokens) external;

Parameters

NameTypeDescription
_mTokensaddress[]The list of addresses of the mToken markets to be enabled

enterMarketsWithSender

Add asset (msg.sender) to be included in account liquidity calculation

function enterMarketsWithSender(address _account) external;

Parameters

NameTypeDescription
_accountaddressThe account to add for

exitMarket

Removes asset from sender's account liquidity calculation

Sender must not have an outstanding borrow balance in the asset, or be providing necessary collateral for an outstanding borrow.

function exitMarket(address _mToken) external;

Parameters

NameTypeDescription
_mTokenaddressThe address of the asset to be removed

claimMalda

Claim all the MALDA accrued by holder in all markets

function claimMalda(address holder) external;

Parameters

NameTypeDescription
holderaddressThe address to claim MALDA for

claimMalda

Claim all the MALDA accrued by holder in the specified markets

function claimMalda(address holder, address[] memory mTokens) external;

Parameters

NameTypeDescription
holderaddressThe address to claim MALDA for
mTokensaddress[]The list of markets to claim MALDA in

claimMalda

Claim all MALDA accrued by the holders

function claimMalda(address[] memory holders, address[] memory mTokens, bool borrowers, bool suppliers) external;

Parameters

NameTypeDescription
holdersaddress[]The addresses to claim MALDA for
mTokensaddress[]The list of markets to claim MALDA in
borrowersboolWhether or not to claim MALDA earned by borrowing
suppliersboolWhether or not to claim MALDA earned by supplying

IOracleOperator

Git Source

Prices are returned in USD

Functions

getPrice

Get the price of a mToken asset

function getPrice(address mToken) external view returns (uint256);

Parameters

NameTypeDescription
mTokenaddressThe mToken to get the price of

Returns

NameTypeDescription
<none>uint256The underlying asset price mantissa (scaled by 1e18). Zero means the price is unavailable.

getUnderlyingPrice

Get the underlying price of a mToken asset

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

Parameters

NameTypeDescription
mTokenaddressThe mToken to get the underlying price of

Returns

NameTypeDescription
<none>uint256The underlying asset price mantissa (scaled by 1e18). Zero means the price is unavailable.

IOwnable

Git Source

Functions

transferOwnership

function transferOwnership(address newOwner) external;

IPauser

Git Source

Inherits: ImTokenOperationTypes

Functions

emergencyPauseMarket

pauses all operations for a market

function emergencyPauseMarket(address _market) external;

Parameters

NameTypeDescription
_marketaddressthe mToken address

emergencyPauseMarketFor

pauses a specific operation for a market

function emergencyPauseMarketFor(address _market, OperationType _pauseType) external;

Parameters

NameTypeDescription
_marketaddressthe mToken address
_pauseTypeOperationTypethe operation type

emergencyPauseAll

pauses all operations for all registered markets

function emergencyPauseAll() external;

Events

PauseAll

event PauseAll();

MarketPaused

event MarketPaused(address indexed market);

MarketRemoved

event MarketRemoved(address indexed market);

MarketAdded

event MarketAdded(address indexed market, PausableType marketType);

MarketPausedFor

event MarketPausedFor(address indexed market, OperationType pauseType);

Errors

Pauser_EntryNotFound

error Pauser_EntryNotFound();

Pauser_NotAuthorized

error Pauser_NotAuthorized();

Pauser_AddressNotValid

error Pauser_AddressNotValid();

Pauser_AlreadyRegistered

error Pauser_AlreadyRegistered();

Pauser_ContractNotEnabled

error Pauser_ContractNotEnabled();

Structs

PausableContract

struct PausableContract {
    address market;
    PausableType contractType;
}

Enums

PausableType

enum PausableType {
    NonPausable,
    Host,
    Extension
}

IRebalanceMarket

Git Source

Functions

extractForRebalancing

function extractForRebalancing(uint256 amount) external;

IRebalancer

Git Source

Functions

nonce

returns current nonce

function nonce() external view returns (uint256);

isBridgeWhitelisted

returns if a bridge implementation is whitelisted

function isBridgeWhitelisted(address bridge) external view returns (bool);

isDestinationWhitelisted

returns if a destination is whitelisted

function isDestinationWhitelisted(uint32 dstId) external view returns (bool);

sendMsg

sends a bridge message

function sendMsg(address bridge, address _market, uint256 _amount, Msg calldata msg) external payable;

Parameters

NameTypeDescription
bridgeaddressthe whitelisted bridge address
_marketaddressthe market to rebalance from address
_amountuint256the amount to rebalance
msgMsgthe message data

Events

BridgeWhitelistedStatusUpdated

event BridgeWhitelistedStatusUpdated(address indexed bridge, bool status);

MsgSent

event MsgSent(
    address indexed bridge, uint32 indexed dstChainId, address indexed token, bytes message, bytes bridgeData
);

EthSaved

event EthSaved(uint256 amount);

MaxTransferSizeUpdated

event MaxTransferSizeUpdated(uint32 indexed dstChainId, address indexed token, uint256 newLimit);

MinTransferSizeUpdated

event MinTransferSizeUpdated(uint32 indexed dstChainId, address indexed token, uint256 newLimit);

DestinationWhitelistedStatusUpdated

event DestinationWhitelistedStatusUpdated(uint32 indexed dstChainId, bool status);

AllowedListUpdated

event AllowedListUpdated(address[] list, bool status);

Errors

Rebalancer_NotAuthorized

error Rebalancer_NotAuthorized();

Rebalancer_MarketNotValid

error Rebalancer_MarketNotValid();

Rebalancer_RequestNotValid

error Rebalancer_RequestNotValid();

Rebalancer_AddressNotValid

error Rebalancer_AddressNotValid();

Rebalancer_BridgeNotWhitelisted

error Rebalancer_BridgeNotWhitelisted();

Rebalancer_TransferSizeExcedeed

error Rebalancer_TransferSizeExcedeed();

Rebalancer_TransferSizeMinNotMet

error Rebalancer_TransferSizeMinNotMet();

Rebalancer_DestinationNotWhitelisted

error Rebalancer_DestinationNotWhitelisted();

Structs

Msg

struct Msg {
    uint32 dstChainId;
    address token;
    bytes message;
    bytes bridgeData;
}

IRewardDistributorData

Git Source

Structs

RewardMarketState

struct RewardMarketState {
    uint256 supplySpeed;
    uint224 supplyIndex;
    uint32 supplyBlock;
    uint256 borrowSpeed;
    uint224 borrowIndex;
    uint32 borrowBlock;
}

RewardAccountState

struct RewardAccountState {
    mapping(address => uint256) supplierIndex;
    mapping(address => uint256) borrowerIndex;
    uint256 rewardAccrued;
}

IRewardDistributor

Git Source

Functions

operator

The operator that rewards are distributed to

function operator() external view returns (address);

isRewardToken

Flag to check if reward token added before

function isRewardToken(address _token) external view returns (bool);

Parameters

NameTypeDescription
_tokenaddressthe token to check for

getRewardTokens

Added reward tokens

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

getBlockTimestamp

Get block timestamp

function getBlockTimestamp() external view returns (uint32);

notifySupplyIndex

Notifies supply index

function notifySupplyIndex(address mToken) external;

notifyBorrowIndex

Notifies borrow index

function notifyBorrowIndex(address mToken) external;

notifySupplier

Notifies supplier

function notifySupplier(address mToken, address supplier) external;

notifyBorrower

Notifies borrower

function notifyBorrower(address mToken, address borrower) external;

claim

Claim tokens for `holders

function claim(address[] memory holders) external;

Parameters

NameTypeDescription
holdersaddress[]the accounts to claim for

Events

RewardAccrued

event RewardAccrued(address indexed rewardToken, address indexed user, uint256 deltaAccrued, uint256 totalAccrued);

RewardGranted

event RewardGranted(address indexed rewardToken, address indexed user, uint256 amount);

SupplySpeedUpdated

event SupplySpeedUpdated(address indexed rewardToken, address indexed mToken, uint256 supplySpeed);

BorrowSpeedUpdated

event BorrowSpeedUpdated(address indexed rewardToken, address indexed mToken, uint256 borrowSpeed);

OperatorSet

event OperatorSet(address indexed oldOperator, address indexed newOperator);

WhitelistedToken

event WhitelistedToken(address indexed token);

SupplyIndexNotified

event SupplyIndexNotified(address indexed rewardToken, address indexed mToken);

BorrowIndexNotified

event BorrowIndexNotified(address indexed rewardToken, address indexed mToken);

IRoles

Git Source

Functions

REBALANCER

Returns REBALANCER role

function REBALANCER() external view returns (bytes32);

REBALANCER_EOA

Returns REBALANCER_EOA role

function REBALANCER_EOA() external view returns (bytes32);

GUARDIAN_PAUSE

Returns GUARDIAN_PAUSE role

function GUARDIAN_PAUSE() external view returns (bytes32);

GUARDIAN_BRIDGE

Returns GUARDIAN_BRIDGE role

function GUARDIAN_BRIDGE() external view returns (bytes32);

GUARDIAN_BORROW_CAP

Returns GUARDIAN_BORROW_CAP role

function GUARDIAN_BORROW_CAP() external view returns (bytes32);

GUARDIAN_SUPPLY_CAP

Returns GUARDIAN_SUPPLY_CAP role

function GUARDIAN_SUPPLY_CAP() external view returns (bytes32);

GUARDIAN_RESERVE

Returns GUARDIAN_RESERVE role

function GUARDIAN_RESERVE() external view returns (bytes32);

PROOF_FORWARDER

Returns PROOF_FORWARDER role

function PROOF_FORWARDER() external view returns (bytes32);

PROOF_BATCH_FORWARDER

Returns PROOF_BATCH_FORWARDER role

function PROOF_BATCH_FORWARDER() external view returns (bytes32);

SEQUENCER

Returns SEQUENCER role

function SEQUENCER() external view returns (bytes32);

PAUSE_MANAGER

Returns PAUSE_MANAGER role

function PAUSE_MANAGER() external view returns (bytes32);

CHAINS_MANAGER

Returns CHAINS_MANAGER role

function CHAINS_MANAGER() external view returns (bytes32);

GUARDIAN_ORACLE

Returns GUARDIAN_ORACLE role

function GUARDIAN_ORACLE() external view returns (bytes32);

isAllowedFor

Returns allowance status for a contract and a role

function isAllowedFor(address _contract, bytes32 _role) external view returns (bool);

Parameters

NameTypeDescription
_contractaddressthe contract address
_rolebytes32the bytes32 role

Errors

Roles_InputNotValid

error Roles_InputNotValid();

ImErc20

Git Source

Functions

mint

Sender supplies assets into the market and receives mTokens in exchange

Accrues interest whether or not the operation succeeds, unless reverted

function mint(uint256 mintAmount, address receiver, uint256 minAmountOut) external;

Parameters

NameTypeDescription
mintAmountuint256The amount of the underlying asset to supply
receiveraddressThe mTokens receiver
minAmountOutuint256The min amounts to be received

redeem

Sender redeems mTokens in exchange for the underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function redeem(uint256 redeemTokens) external;

Parameters

NameTypeDescription
redeemTokensuint256The number of mTokens to redeem into underlying

redeemUnderlying

Sender redeems mTokens in exchange for a specified amount of underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function redeemUnderlying(uint256 redeemAmount) external;

Parameters

NameTypeDescription
redeemAmountuint256The amount of underlying to redeem

borrow

Sender borrows assets from the protocol to their own address

function borrow(uint256 borrowAmount) external;

Parameters

NameTypeDescription
borrowAmountuint256The amount of the underlying asset to borrow

repay

Sender repays their own borrow

function repay(uint256 repayAmount) external returns (uint256);

Parameters

NameTypeDescription
repayAmountuint256The amount to repay, or type(uint256).max for the full outstanding amount

repayBehalf

Sender repays a borrow belonging to borrower

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

Parameters

NameTypeDescription
borroweraddressthe account with the debt being payed off
repayAmountuint256The amount to repay, or type(uint256).max for the full outstanding amount

liquidate

The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.

function liquidate(address borrower, uint256 repayAmount, address mTokenCollateral) external;

Parameters

NameTypeDescription
borroweraddressThe borrower of this mToken to be liquidated
repayAmountuint256The amount of the underlying borrowed asset to repay
mTokenCollateraladdressThe market in which to seize collateral from the borrower

addReserves

The sender adds to reserves.

function addReserves(uint256 addAmount) external;

Parameters

NameTypeDescription
addAmountuint256The amount fo underlying token to add as reserves

ImErc20Host

Git Source

Functions

isCallerAllowed

Returns if a caller is allowed for sender

function isCallerAllowed(address sender, address caller) external view returns (bool);

getProofData

Returns the proof data journal

function getProofData(address user, uint32 dstId) external view returns (uint256, uint256);

mintMigration

Mints mTokens during migration without requiring underlying transfer

function mintMigration(uint256 amount, uint256 minAmount, address receiver) external;

Parameters

NameTypeDescription
amountuint256The amount of underlying to be accounted for
minAmountuint256The min amount of underlying to be accounted for
receiveraddressThe address that will receive the mTokens

borrowMigration

Borrows from market for a specific borrower and not msg.sender

function borrowMigration(uint256 amount, address borrower, address receiver) external;

Parameters

NameTypeDescription
amountuint256The amount of underlying to be accounted for
borroweraddressThe address that borrow is executed for
receiveraddress

extractForRebalancing

Extract amount to be used for rebalancing operation

function extractForRebalancing(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The amount to rebalance

updateAllowedCallerStatus

Set caller status for msg.sender

function updateAllowedCallerStatus(address caller, bool status) external;

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

liquidateExternal

Mints tokens after external verification

function liquidateExternal(
    bytes calldata journalData,
    bytes calldata seal,
    address[] calldata userToLiquidate,
    uint256[] calldata liquidateAmount,
    address[] calldata collateral,
    address receiver
) external;

Parameters

NameTypeDescription
journalDatabytesThe journal data for minting (array of encoded journals)
sealbytesThe Zk proof seal
userToLiquidateaddress[]Array of positions to liquidate
liquidateAmountuint256[]Array of amounts to liquidate
collateraladdress[]Array of collaterals to seize
receiveraddressThe collateral receiver

mintExternal

Mints tokens after external verification

function mintExternal(
    bytes calldata journalData,
    bytes calldata seal,
    uint256[] calldata mintAmount,
    uint256[] calldata minAmountsOut,
    address receiver
) external;

Parameters

NameTypeDescription
journalDatabytesThe journal data for minting (array of encoded journals)
sealbytesThe Zk proof seal
mintAmountuint256[]Array of amounts to mint
minAmountsOutuint256[]Array of min amounts accepted
receiveraddressThe tokens receiver

repayExternal

Repays tokens after external verification

function repayExternal(
    bytes calldata journalData,
    bytes calldata seal,
    uint256[] calldata repayAmount,
    address receiver
) external;

Parameters

NameTypeDescription
journalDatabytesThe journal data for repayment (array of encoded journals)
sealbytesThe Zk proof seal
repayAmountuint256[]Array of amounts to repay
receiveraddressThe position to repay for

withdrawOnExtension

Initiates a withdraw operation

function withdrawOnExtension(uint256 amount, uint32 dstChainId) external payable;

Parameters

NameTypeDescription
amountuint256The amount to withdraw
dstChainIduint32The destination chain to recieve funds

borrowOnExtension

Initiates a withdraw operation

function borrowOnExtension(uint256 amount, uint32 dstChainId) external payable;

Parameters

NameTypeDescription
amountuint256The amount to withdraw
dstChainIduint32The destination chain to recieve funds

Events

AllowedCallerUpdated

Emitted when a user updates allowed callers

event AllowedCallerUpdated(address indexed sender, address indexed caller, bool status);

mErc20Host_ChainStatusUpdated

Emitted when a chain id whitelist status is updated

event mErc20Host_ChainStatusUpdated(uint32 indexed chainId, bool status);

mErc20Host_LiquidateExternal

Emitted when a liquidate operation is executed

event mErc20Host_LiquidateExternal(
    address indexed msgSender,
    address indexed srcSender,
    address userToLiquidate,
    address receiver,
    address indexed collateral,
    uint32 srcChainId,
    uint256 amount
);

mErc20Host_MintExternal

Emitted when a mint operation is executed

event mErc20Host_MintExternal(
    address indexed msgSender, address indexed srcSender, address indexed receiver, uint32 chainId, uint256 amount
);

mErc20Host_BorrowExternal

Emitted when a borrow operation is executed

event mErc20Host_BorrowExternal(
    address indexed msgSender, address indexed srcSender, uint32 indexed chainId, uint256 amount
);

mErc20Host_RepayExternal

Emitted when a repay operation is executed

event mErc20Host_RepayExternal(
    address indexed msgSender, address indexed srcSender, address indexed position, uint32 chainId, uint256 amount
);

mErc20Host_WithdrawExternal

Emitted when a withdrawal is executed

event mErc20Host_WithdrawExternal(
    address indexed msgSender, address indexed srcSender, uint32 indexed chainId, uint256 amount
);

mErc20Host_BorrowOnExtensionChain

Emitted when a borrow operation is triggered for an extension chain

event mErc20Host_BorrowOnExtensionChain(address indexed sender, uint32 dstChainId, uint256 amount);

mErc20Host_WithdrawOnExtensionChain

Emitted when a withdraw operation is triggered for an extension chain

event mErc20Host_WithdrawOnExtensionChain(address indexed sender, uint32 dstChainId, uint256 amount);

mErc20Host_GasFeeUpdated

Emitted when gas fees are updated for a dst chain

event mErc20Host_GasFeeUpdated(uint32 indexed dstChainId, uint256 amount);

mErc20Host_MintMigration

event mErc20Host_MintMigration(address indexed receiver, uint256 amount);

mErc20Host_BorrowMigration

event mErc20Host_BorrowMigration(address indexed borrower, uint256 amount);

Errors

mErc20Host_ProofGenerationInputNotValid

Thrown when the chain id is not LINEA

error mErc20Host_ProofGenerationInputNotValid();

mErc20Host_DstChainNotValid

Thrown when the dst chain id is not current chain

error mErc20Host_DstChainNotValid();

mErc20Host_ChainNotValid

Thrown when the chain id is not LINEA

error mErc20Host_ChainNotValid();

mErc20Host_AddressNotValid

Thrown when the address is not valid

error mErc20Host_AddressNotValid();

mErc20Host_AmountTooBig

Thrown when the amount provided is bigger than the available amount`

error mErc20Host_AmountTooBig();

mErc20Host_AmountNotValid

Thrown when the amount specified is invalid (e.g., zero)

error mErc20Host_AmountNotValid();

mErc20Host_JournalNotValid

Thrown when the journal data provided is invalid or corrupted

error mErc20Host_JournalNotValid();

mErc20Host_CallerNotAllowed

Thrown when caller is not allowed

error mErc20Host_CallerNotAllowed();

mErc20Host_NotRebalancer

Thrown when caller is not rebalancer

error mErc20Host_NotRebalancer();

mErc20Host_LengthMismatch

Thrown when length of array is not valid

error mErc20Host_LengthMismatch();

mErc20Host_NotEnoughGasFee

Thrown when not enough gas fee was received

error mErc20Host_NotEnoughGasFee();

mErc20Host_L1InclusionRequired

Thrown when L1 inclusion is required

error mErc20Host_L1InclusionRequired();

ImTokenOperationTypes

Git Source

Enums

OperationType

enum OperationType {
    AmountIn,
    AmountInHere,
    AmountOut,
    AmountOutHere,
    Seize,
    Transfer,
    Mint,
    Borrow,
    Repay,
    Redeem,
    Liquidate,
    Rebalancing
}

ImTokenDelegator

Git Source

Functions

delegate

Non-standard token able to delegate

function delegate(address delegatee) external;

ImTokenMinimal

Git Source

Functions

name

EIP-20 token name for this token

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

symbol

EIP-20 token symbol for this token

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

decimals

EIP-20 token decimals for this token

function decimals() external view returns (uint8);

totalSupply

Returns the value of tokens in existence.

function totalSupply() external view returns (uint256);

totalUnderlying

Returns the amount of underlying tokens

function totalUnderlying() external view returns (uint256);

balanceOf

Returns the value of tokens owned by account.

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

Parameters

NameTypeDescription
accountaddressThe account to check for

isMToken

Returns true

function isMToken() external view returns (bool);

underlying

Returns the underlying address

function underlying() external view returns (address);

ImToken

Git Source

Inherits: ImTokenMinimal

Functions

rolesOperator

Roles manager

function rolesOperator() external view returns (IRoles);

admin

Administrator for this contract

function admin() external view returns (address payable);

pendingAdmin

Pending administrator for this contract

function pendingAdmin() external view returns (address payable);

operator

Contract which oversees inter-mToken operations

function operator() external view returns (address);

interestRateModel

Model which tells what the current interest rate should be

function interestRateModel() external view returns (address);

reserveFactorMantissa

Fraction of interest currently set aside for reserves

function reserveFactorMantissa() external view returns (uint256);

accrualBlockTimestamp

Block timestamp that interest was last accrued at

function accrualBlockTimestamp() external view returns (uint256);

borrowIndex

Accumulator of the total earned interest rate since the opening of the market

function borrowIndex() external view returns (uint256);

totalBorrows

Total amount of outstanding borrows of the underlying in this market

function totalBorrows() external view returns (uint256);

totalReserves

Total amount of reserves of the underlying held in this market

function totalReserves() external view returns (uint256);

sameChainFlowStateDisabled

Returns true/false for same chain flow state disable status

function sameChainFlowStateDisabled() external view returns (bool);

transfer

Transfers amount tokens to the dst address

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

Parameters

NameTypeDescription
dstaddressThe address of the recipient
amountuint256The number of tokens to transfer

Returns

NameTypeDescription
<none>boolWhether the transfer was successful or not

transferFrom

Transfers amount tokens from the src address to the dst address

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

Parameters

NameTypeDescription
srcaddressThe address from which tokens are transferred
dstaddressThe address to which tokens are transferred
amountuint256The number of tokens to transfer

Returns

NameTypeDescription
<none>boolWhether the transfer was successful or not

approve

Approves spender to spend amount tokens on behalf of the caller

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

Parameters

NameTypeDescription
spenderaddressThe address authorized to spend tokens
amountuint256The number of tokens to approve

Returns

NameTypeDescription
<none>boolWhether the approval was successful or not

allowance

Returns the current allowance the spender has from the owner

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

Parameters

NameTypeDescription
owneraddressThe address of the token holder
spenderaddressThe address authorized to spend the tokens

Returns

NameTypeDescription
<none>uint256The current remaining number of tokens spender can spend

balanceOf

Returns the balance of tokens held by owner

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

Parameters

NameTypeDescription
owneraddressThe address to query the balance for

Returns

NameTypeDescription
<none>uint256The balance of tokens owned by owner

balanceOfUnderlying

Returns the underlying asset balance of the owner

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

Parameters

NameTypeDescription
owneraddressThe address to query the balance of underlying assets for

Returns

NameTypeDescription
<none>uint256The balance of underlying assets owned by owner

getAccountSnapshot

Returns the snapshot of account details for the given account

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

Parameters

NameTypeDescription
accountaddressThe address to query the account snapshot for

Returns

NameTypeDescription
<none>uint256(token balance, borrow balance, exchange rate)
<none>uint256
<none>uint256

borrowRatePerBlock

Returns the current borrow rate per block

function borrowRatePerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The current borrow rate per block, scaled by 1e18

supplyRatePerBlock

Returns the current supply rate per block

function supplyRatePerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The current supply rate per block, scaled by 1e18

totalBorrowsCurrent

Returns the total amount of borrows, accounting for interest

function totalBorrowsCurrent() external returns (uint256);

Returns

NameTypeDescription
<none>uint256The total amount of borrows

borrowBalanceCurrent

Returns the current borrow balance for account, accounting for interest

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

Parameters

NameTypeDescription
accountaddressThe address to query the borrow balance for

Returns

NameTypeDescription
<none>uint256The current borrow balance

borrowBalanceStored

Returns the stored borrow balance for account, without accruing interest

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

Parameters

NameTypeDescription
accountaddressThe address to query the stored borrow balance for

Returns

NameTypeDescription
<none>uint256The stored borrow balance

exchangeRateCurrent

Returns the current exchange rate, with interest accrued

function exchangeRateCurrent() external returns (uint256);

Returns

NameTypeDescription
<none>uint256The current exchange rate

exchangeRateStored

Returns the stored exchange rate, without accruing interest

function exchangeRateStored() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The stored exchange rate

getCash

Returns the total amount of available cash in the contract

function getCash() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total amount of cash

accrueInterest

Accrues interest on the contract's outstanding loans

function accrueInterest() external;

seize

Transfers collateral tokens (this market) to the liquidator.

Will fail unless called by another mToken during the process of liquidation. Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.

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

Parameters

NameTypeDescription
liquidatoraddressThe account receiving seized collateral
borroweraddressThe account having collateral seized
seizeTokensuint256The number of mTokens to seize

reduceReserves

Accrues interest and reduces reserves by transferring to admin

function reduceReserves(uint256 reduceAmount) external;

Parameters

NameTypeDescription
reduceAmountuint256Amount of reduction to reserves

ImTokenGateway

Git Source

Functions

rolesOperator

Roles manager

function rolesOperator() external view returns (IRoles);

underlying

Returns the address of the underlying token

function underlying() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the underlying token

isPaused

returns pause state for operation

function isPaused(ImTokenOperationTypes.OperationType _type) external view returns (bool);

Parameters

NameTypeDescription
_typeImTokenOperationTypes.OperationTypethe operation type

accAmountIn

Returns accumulated amount in per user

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

accAmountOut

Returns accumulated amount out per user

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

isCallerAllowed

Returns if a caller is allowed for sender

function isCallerAllowed(address sender, address caller) external view returns (bool);

getProofData

Returns the proof data journal

function getProofData(address user, uint32 dstId) external view returns (uint256, uint256);

extractForRebalancing

Extract amount to be used for rebalancing operation

function extractForRebalancing(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The amount to rebalance

setPaused

Set pause for a specific operation

function setPaused(ImTokenOperationTypes.OperationType _type, bool state) external;

Parameters

NameTypeDescription
_typeImTokenOperationTypes.OperationTypeThe pause operation type
stateboolThe pause operation status

updateAllowedCallerStatus

Set caller status for msg.sender

function updateAllowedCallerStatus(address caller, bool status) external;

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

supplyOnHost

Supply underlying to the contract

function supplyOnHost(uint256 amount, address receiver, bytes4 lineaSelector) external payable;

Parameters

NameTypeDescription
amountuint256The supplied amount
receiveraddressThe receiver address
lineaSelectorbytes4The method selector to be called on Linea by our relayer. If empty, user has to submit it

outHere

Extract tokens

function outHere(bytes calldata journalData, bytes calldata seal, uint256[] memory amounts, address receiver)
    external;

Parameters

NameTypeDescription
journalDatabytesThe supplied journal
sealbytesThe seal address
amountsuint256[]The amounts to withdraw for each journal
receiveraddressThe receiver address

Events

AllowedCallerUpdated

Emitted when a user updates allowed callers

event AllowedCallerUpdated(address indexed sender, address indexed caller, bool status);

mTokenGateway_Supplied

Emitted when a supply operation is initiated

event mTokenGateway_Supplied(
    address indexed from,
    address indexed receiver,
    uint256 accAmountIn,
    uint256 accAmountOut,
    uint256 amount,
    uint32 srcChainId,
    uint32 dstChainId,
    bytes4 lineaMethodSelector
);

mTokenGateway_Extracted

Emitted when an extract was finalized

event mTokenGateway_Extracted(
    address indexed msgSender,
    address indexed srcSender,
    address indexed receiver,
    uint256 accAmountIn,
    uint256 accAmountOut,
    uint256 amount,
    uint32 srcChainId,
    uint32 dstChainId
);

mTokenGateway_Skipped

Emitted when a proof was skipped

event mTokenGateway_Skipped(
    address indexed msgSender,
    address indexed srcSender,
    address indexed receiver,
    uint256 accAmountIn,
    uint256 accAmountOut,
    uint256 amount,
    uint32 srcChainId,
    uint32 dstChainId
);

mTokenGateway_GasFeeUpdated

Emitted when the gas fee is updated

event mTokenGateway_GasFeeUpdated(uint256 amount);

mTokenGateway_PausedState

event mTokenGateway_PausedState(ImTokenOperationTypes.OperationType indexed _type, bool _status);

ZkVerifierUpdated

event ZkVerifierUpdated(address indexed oldVerifier, address indexed newVerifier);

mTokenGateway_UserWhitelisted

event mTokenGateway_UserWhitelisted(address indexed user, bool status);

mTokenGateway_WhitelistEnabled

event mTokenGateway_WhitelistEnabled();

mTokenGateway_WhitelistDisabled

event mTokenGateway_WhitelistDisabled();

Errors

mTokenGateway_ChainNotValid

Thrown when the chain id is not LINEA

error mTokenGateway_ChainNotValid();

mTokenGateway_AddressNotValid

Thrown when the address is not valid

error mTokenGateway_AddressNotValid();

mTokenGateway_AmountNotValid

Thrown when the amount specified is invalid (e.g., zero)

error mTokenGateway_AmountNotValid();

mTokenGateway_JournalNotValid

Thrown when the journal data provided is invalid

error mTokenGateway_JournalNotValid();

mTokenGateway_AmountTooBig

Thrown when there is insufficient cash to release the specified amount

error mTokenGateway_AmountTooBig();

mTokenGateway_ReleaseCashNotAvailable

Thrown when there is insufficient cash to release the specified amount

error mTokenGateway_ReleaseCashNotAvailable();

mTokenGateway_NonTransferable

Thrown when token is tranferred

error mTokenGateway_NonTransferable();

mTokenGateway_CallerNotAllowed

Thrown when caller is not allowed

error mTokenGateway_CallerNotAllowed();

mTokenGateway_Paused

Thrown when market is paused for operation type

error mTokenGateway_Paused(ImTokenOperationTypes.OperationType _type);

mTokenGateway_NotRebalancer

Thrown when caller is not rebalancer

error mTokenGateway_NotRebalancer();

mTokenGateway_LengthNotValid

Thrown when length is not valid

error mTokenGateway_LengthNotValid();

mTokenGateway_NotEnoughGasFee

Thrown when not enough gas fee was received

error mTokenGateway_NotEnoughGasFee();

mTokenGateway_L1InclusionRequired

Thrown when L1 inclusion is required

error mTokenGateway_L1InclusionRequired();

mTokenGateway_UserNotWhitelisted

Thrown when user is not whitelisted

error mTokenGateway_UserNotWhitelisted();

Contents

Bytes32AddressLib

Git Source

Author: Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Bytes32AddressLib.sol)

Library for converting between addresses and bytes32 values.

Functions

fromLast20Bytes

function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address);

fillLast12Bytes

function fillLast12Bytes(address addressValue) internal pure returns (bytes32);

BytesLib

Git Source

Functions

concat

function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory);

concatStorage

function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal;

slice

function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory);

toAddress

function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address);

toUint8

function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8);

toUint16

function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16);

toUint32

function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32);

toUint64

function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64);

toUint96

function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96);

toUint128

function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128);

toUint256

function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256);

toBytes32

function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32);

equal

function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool);

equal_nonAligned

function equal_nonAligned(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool);

equalStorage

function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool);

CREATE3

Git Source

Authors: Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/CREATE3.sol), Modified from 0xSequence (https://github.com/0xSequence/create3/blob/master/contracts/Create3.sol)

Deploy to deterministic addresses without an initcode factor.

State Variables

PROXY_BYTECODE

bytes internal constant PROXY_BYTECODE = hex"67363d3d37363d34f03d5260086018f3";

PROXY_BYTECODE_HASH

bytes32 internal constant PROXY_BYTECODE_HASH = keccak256(PROXY_BYTECODE);

Functions

deploy

function deploy(bytes32 salt, bytes memory creationCode, uint256 value) internal returns (address deployed);

getDeployed

function getDeployed(bytes32 salt) internal view returns (address);

IToken

Git Source

Functions

approve

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

SafeApprove

Git Source

Functions

safeApprove

function safeApprove(address token, address to, uint256 value) internal;

Errors

SafeApprove_NoContract

error SafeApprove_NoContract();

SafeApprove_Failed

error SafeApprove_Failed();

mTokenProofDecoderLib

Git Source

State Variables

ENTRY_SIZE

uint256 public constant ENTRY_SIZE = 113;

Functions

decodeJournal

function decodeJournal(bytes memory journalData)
    internal
    pure
    returns (
        address sender,
        address market,
        uint256 accAmountIn,
        uint256 accAmountOut,
        uint32 chainId,
        uint32 dstChainId,
        bool L1inclusion
    );

encodeJournal

function encodeJournal(
    address sender,
    address market,
    uint256 accAmountIn,
    uint256 accAmountOut,
    uint32 chainId,
    uint32 dstChainId,
    bool L1inclusion
) internal pure returns (bytes memory);

Errors

mTokenProofDecoderLib_ChainNotFound

error mTokenProofDecoderLib_ChainNotFound();

mTokenProofDecoderLib_InvalidLength

error mTokenProofDecoderLib_InvalidLength();

mTokenProofDecoderLib_InvalidInclusion

error mTokenProofDecoderLib_InvalidInclusion();

Contents

Contents

mTokenGateway

Git Source

Inherits: OwnableUpgradeable, ImTokenGateway, ImTokenOperationTypes

State Variables

rolesOperator

Roles manager

IRoles public rolesOperator;

verifier

IZkVerifier public verifier;

paused

mapping(OperationType => bool) public paused;

underlying

Returns the address of the underlying token

address public underlying;

accAmountIn

mapping(address => uint256) public accAmountIn;

accAmountOut

mapping(address => uint256) public accAmountOut;

allowedCallers

mapping(address => mapping(address => bool)) public allowedCallers;

userWhitelisted

mapping(address => bool) public userWhitelisted;

whitelistEnabled

bool public whitelistEnabled;

LINEA_CHAIN_ID

uint32 private constant LINEA_CHAIN_ID = 59144;

gasFee

gas fee for supplyOnHost

uint256 public gasFee;

Functions

constructor

Note: oz-upgrades-unsafe-allow: constructor

constructor();

initialize

function initialize(address payable _owner, address _underlying, address _roles, address zkVerifier_)
    external
    initializer;

notPaused

modifier notPaused(OperationType _type);

onlyAllowedUser

modifier onlyAllowedUser(address user);

isPaused

returns pause state for operation

function isPaused(OperationType _type) external view returns (bool);

Parameters

NameTypeDescription
_typeOperationTypethe operation type

isCallerAllowed

Returns if a caller is allowed for sender

function isCallerAllowed(address sender, address caller) external view returns (bool);

getProofData

Returns the proof data journal

function getProofData(address user, uint32) external view returns (uint256, uint256);

setWhitelistedUser

Sets user whitelist status

function setWhitelistedUser(address user, bool state) external onlyOwner;

Parameters

NameTypeDescription
useraddressThe user address
stateboolThe new staate

enableWhitelist

Enable user whitelist

function enableWhitelist() external onlyOwner;

disableWhitelist

Disable user whitelist

function disableWhitelist() external onlyOwner;

setPaused

Set pause for a specific operation

function setPaused(OperationType _type, bool state) external override;

Parameters

NameTypeDescription
_typeOperationTypeThe pause operation type
stateboolThe pause operation status

extractForRebalancing

Extract amount to be used for rebalancing operation

function extractForRebalancing(uint256 amount) external notPaused(OperationType.Rebalancing);

Parameters

NameTypeDescription
amountuint256The amount to rebalance

setUnderlying

function setUnderlying(address _addr) external onlyOwner;

setGasFee

Sets the gas fee

function setGasFee(uint256 amount) external onlyOwner;

Parameters

NameTypeDescription
amountuint256the new gas fee

withdrawGasFees

Withdraw gas received so far

function withdrawGasFees(address payable receiver) external;

Parameters

NameTypeDescription
receiveraddress payablethe receiver address

updateZkVerifier

Updates IZkVerifier address

function updateZkVerifier(address _zkVerifier) external onlyOwner;

Parameters

NameTypeDescription
_zkVerifieraddressthe verifier address

updateAllowedCallerStatus

Set caller status for msg.sender

function updateAllowedCallerStatus(address caller, bool status) external override;

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

supplyOnHost

Supply underlying to the contract

function supplyOnHost(uint256 amount, address receiver, bytes4 lineaSelector)
    external
    payable
    override
    notPaused(OperationType.AmountIn)
    onlyAllowedUser(msg.sender);

Parameters

NameTypeDescription
amountuint256The supplied amount
receiveraddressThe receiver address
lineaSelectorbytes4The method selector to be called on Linea by our relayer. If empty, user has to submit it

outHere

Extract tokens

function outHere(bytes calldata journalData, bytes calldata seal, uint256[] calldata amounts, address receiver)
    external
    notPaused(OperationType.AmountOutHere);

Parameters

NameTypeDescription
journalDatabytesThe supplied journal
sealbytesThe seal address
amountsuint256[]The amounts to withdraw for each journal
receiveraddressThe receiver address

_outHere

function _outHere(bytes memory journalData, uint256 amount, address receiver) internal;

_verifyProof

function _verifyProof(bytes calldata journalData, bytes calldata seal) private view;

_checkSender

function _checkSender(address msgSender, address srcSender) private view;

_getSequencerRole

function _getSequencerRole() private view returns (bytes32);

_getBatchProofForwarderRole

function _getBatchProofForwarderRole() private view returns (bytes32);

_getProofForwarderRole

function _getProofForwarderRole() private view returns (bytes32);

_isAllowedFor

function _isAllowedFor(address _sender, bytes32 role) private view returns (bool);

Contents

mErc20Host

Git Source

Inherits: mErc20Upgradable, ImErc20Host, ImTokenOperationTypes

State Variables

FLASH_MINT_CALLBACK_SUCCESS

bytes4 private constant FLASH_MINT_CALLBACK_SUCCESS = bytes4(keccak256("onFlashMint(address,uint256,bytes)"));

migrator

address public migrator;

accAmountInPerChain

mapping(uint32 => mapping(address => uint256)) public accAmountInPerChain;

accAmountOutPerChain

mapping(uint32 => mapping(address => uint256)) public accAmountOutPerChain;

allowedCallers

mapping(address => mapping(address => bool)) public allowedCallers;

allowedChains

mapping(uint32 => bool) public allowedChains;

gasFees

mapping(uint32 => uint256) public gasFees;

verifier

IZkVerifier public verifier;

Functions

onlyMigrator

modifier onlyMigrator();

initialize

Initializes the new money market

function initialize(
    address underlying_,
    address operator_,
    address interestRateModel_,
    uint256 initialExchangeRateMantissa_,
    string memory name_,
    string memory symbol_,
    uint8 decimals_,
    address payable admin_,
    address zkVerifier_,
    address roles_
) external initializer;

Parameters

NameTypeDescription
underlying_addressThe address of the underlying asset
operator_addressThe address of the Operator
interestRateModel_addressThe address of the interest rate model
initialExchangeRateMantissa_uint256The initial exchange rate, scaled by 1e18
name_stringERC-20 name of this token
symbol_stringERC-20 symbol of this token
decimals_uint8ERC-20 decimal precision of this token
admin_address payableAddress of the administrator of this token
zkVerifier_addressThe IZkVerifier address
roles_address

isCallerAllowed

Returns if a caller is allowed for sender

function isCallerAllowed(address sender, address caller) external view returns (bool);

getProofData

Returns the proof data journal

function getProofData(address user, uint32 dstId) external view returns (uint256, uint256);

updateAllowedChain

Updates an allowed chain status

function updateAllowedChain(uint32 _chainId, bool _status) external;

Parameters

NameTypeDescription
_chainIduint32the chain id
_statusboolthe new status

extractForRebalancing

Extract amount to be used for rebalancing operation

function extractForRebalancing(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The amount to rebalance

setMigrator

Sets the migrator address

function setMigrator(address _migrator) external onlyAdmin;

Parameters

NameTypeDescription
_migratoraddressThe new migrator address

setGasFee

Sets the gas fee

function setGasFee(uint32 dstChainId, uint256 amount) external onlyAdmin;

Parameters

NameTypeDescription
dstChainIduint32the destination chain id
amountuint256the gas fee amount

withdrawGasFees

Withdraw gas received so far

function withdrawGasFees(address payable receiver) external;

Parameters

NameTypeDescription
receiveraddress payablethe receiver address

updateZkVerifier

Updates IZkVerifier address

function updateZkVerifier(address _zkVerifier) external onlyAdmin;

Parameters

NameTypeDescription
_zkVerifieraddressthe verifier address

updateAllowedCallerStatus

Set caller status for msg.sender

function updateAllowedCallerStatus(address caller, bool status) external override;

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

liquidateExternal

Mints tokens after external verification

function liquidateExternal(
    bytes calldata journalData,
    bytes calldata seal,
    address[] calldata userToLiquidate,
    uint256[] calldata liquidateAmount,
    address[] calldata collateral,
    address receiver
) external override;

Parameters

NameTypeDescription
journalDatabytesThe journal data for minting (array of encoded journals)
sealbytesThe Zk proof seal
userToLiquidateaddress[]Array of positions to liquidate
liquidateAmountuint256[]Array of amounts to liquidate
collateraladdress[]Array of collaterals to seize
receiveraddressThe collateral receiver

mintExternal

Mints tokens after external verification

function mintExternal(
    bytes calldata journalData,
    bytes calldata seal,
    uint256[] calldata mintAmount,
    uint256[] calldata minAmountsOut,
    address receiver
) external override;

Parameters

NameTypeDescription
journalDatabytesThe journal data for minting (array of encoded journals)
sealbytesThe Zk proof seal
mintAmountuint256[]Array of amounts to mint
minAmountsOutuint256[]Array of min amounts accepted
receiveraddressThe tokens receiver

repayExternal

Repays tokens after external verification

function repayExternal(
    bytes calldata journalData,
    bytes calldata seal,
    uint256[] calldata repayAmount,
    address receiver
) external override;

Parameters

NameTypeDescription
journalDatabytesThe journal data for repayment (array of encoded journals)
sealbytesThe Zk proof seal
repayAmountuint256[]Array of amounts to repay
receiveraddressThe position to repay for

withdrawOnExtension

Initiates a withdraw operation

amount represents the number of mTokens to redeem

function withdrawOnExtension(uint256 amount, uint32 dstChainId) external payable override;

Parameters

NameTypeDescription
amountuint256The amount to withdraw
dstChainIduint32The destination chain to recieve funds

borrowOnExtension

Initiates a withdraw operation

function borrowOnExtension(uint256 amount, uint32 dstChainId) external payable override;

Parameters

NameTypeDescription
amountuint256The amount to withdraw
dstChainIduint32The destination chain to recieve funds

mintMigration

Mints mTokens during migration without requiring underlying transfer

function mintMigration(uint256 amount, uint256 minAmount, address receiver) external onlyMigrator;

Parameters

NameTypeDescription
amountuint256The amount of underlying to be accounted for
minAmountuint256The min amount of underlying to be accounted for
receiveraddressThe address that will receive the mTokens

borrowMigration

Borrows from market for a specific borrower and not msg.sender

function borrowMigration(uint256 amount, address borrower, address receiver) external onlyMigrator;

Parameters

NameTypeDescription
amountuint256The amount of underlying to be accounted for
borroweraddressThe address that borrow is executed for
receiveraddress

_computeTotalOutflowAmount

function _computeTotalOutflowAmount(uint256[] calldata amounts) private pure returns (uint256);

_checkOutflow

function _checkOutflow(uint256 amount) private;

_isAllowedFor

function _isAllowedFor(address _sender, bytes32 role) private view returns (bool);

_getProofForwarderRole

function _getProofForwarderRole() private view returns (bytes32);

_getBatchProofForwarderRole

function _getBatchProofForwarderRole() private view returns (bytes32);

_getSequencerRole

function _getSequencerRole() private view returns (bytes32);

_verifyProof

function _verifyProof(bytes calldata journalData, bytes calldata seal) private view;

_checkSender

function _checkSender(address msgSender, address srcSender) private view;

_liquidateExternal

function _liquidateExternal(
    bytes memory singleJournal,
    address userToLiquidate,
    uint256 liquidateAmount,
    address collateral,
    address receiver
) internal;

_mintExternal

function _mintExternal(bytes memory singleJournal, uint256 mintAmount, uint256 minAmountOut, address receiver)
    internal;

_repayExternal

function _repayExternal(bytes memory singleJournal, uint256 repayAmount, address receiver) internal;

BatchSubmitter

Git Source

Inherits: Ownable

State Variables

rolesOperator

The roles contract for access control

IRoles public immutable rolesOperator;

verifier

IZkVerifier public verifier;

MINT_SELECTOR

bytes4 internal constant MINT_SELECTOR = ImErc20Host.mintExternal.selector;

REPAY_SELECTOR

bytes4 internal constant REPAY_SELECTOR = ImErc20Host.repayExternal.selector;

OUT_HERE_SELECTOR

bytes4 internal constant OUT_HERE_SELECTOR = ImTokenGateway.outHere.selector;

Functions

constructor

constructor(address _roles, address _zkVerifier, address _owner) Ownable(_owner);

updateZkVerifier

Updates IZkVerifier address

function updateZkVerifier(address _zkVerifier) external onlyOwner;

Parameters

NameTypeDescription
_zkVerifieraddressthe verifier address

batchProcess

Execute multiple operations in a single transaction

function batchProcess(BatchProcessMsg calldata data) external;

_verifyProof

Verifies the proof using ZkVerifier

function _verifyProof(bytes calldata journalData, bytes calldata seal) private view;

Parameters

NameTypeDescription
journalDatabytesThe journal data to verify
sealbytesThe seal data for verification

Events

BatchProcessFailed

event BatchProcessFailed(
    bytes32 initHash,
    address receiver,
    address mToken,
    uint256 amount,
    uint256 minAmountOut,
    bytes4 selector,
    bytes reason
);

BatchProcessSuccess

event BatchProcessSuccess(
    bytes32 initHash, address receiver, address mToken, uint256 amount, uint256 minAmountOut, bytes4 selector
);

ZkVerifierUpdated

event ZkVerifierUpdated(address indexed oldVerifier, address indexed newVerifier);

Errors

BatchSubmitter_CallerNotAllowed

error BatchSubmitter_CallerNotAllowed();

BatchSubmitter_JournalNotValid

error BatchSubmitter_JournalNotValid();

BatchSubmitter_InvalidSelector

error BatchSubmitter_InvalidSelector();

BatchSubmitter_AddressNotValid

error BatchSubmitter_AddressNotValid();

Structs

BatchProcessMsg

receiver Funds receiver/performed on journalData The encoded journal data seal The seal data for verification mTokens Array of mToken addresses amounts Array of amounts for each operation selectors Array of function selectors for each operation startIndex Start index for processing journals endIndex End index for processing journals (exclusive)

struct BatchProcessMsg {
    address[] receivers;
    bytes journalData;
    bytes seal;
    address[] mTokens;
    uint256[] amounts;
    uint256[] minAmountsOut;
    bytes4[] selectors;
    bytes32[] initHashes;
    uint256 startIndex;
}

mErc20

Git Source

Inherits: mToken, ImErc20

mTokens which wrap an EIP-20 underlying

State Variables

underlying

Underlying asset for this mToken

address public underlying;

Functions

_initializeMErc20

Initialize the new money market

function _initializeMErc20(
    address underlying_,
    address operator_,
    address interestRateModel_,
    uint256 initialExchangeRateMantissa_,
    string memory name_,
    string memory symbol_,
    uint8 decimals_
) internal;

Parameters

NameTypeDescription
underlying_addressThe address of the underlying asset
operator_addressThe address of the Operator
interestRateModel_addressThe address of the interest rate model
initialExchangeRateMantissa_uint256The initial exchange rate, scaled by 1e18
name_stringERC-20 name of this token
symbol_stringERC-20 symbol of this token
decimals_uint8ERC-20 decimal precision of this token

checkSameChainAllowed

modifier checkSameChainAllowed();

delegateMaldaLikeTo

Admin call to delegate the votes of the MALDA-like underlying

mTokens whose underlying are not should revert here

function delegateMaldaLikeTo(address delegatee) external onlyAdmin;

Parameters

NameTypeDescription
delegateeaddressThe address to delegate votes to

sweepToken

A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)

function sweepToken(IERC20 token) external onlyAdmin;

Parameters

NameTypeDescription
tokenIERC20The address of the ERC-20 token to sweep

mint

Sender supplies assets into the market and receives mTokens in exchange

Accrues interest whether or not the operation succeeds, unless reverted

function mint(uint256 mintAmount, address receiver, uint256 minAmountOut) external checkSameChainAllowed;

Parameters

NameTypeDescription
mintAmountuint256The amount of the underlying asset to supply
receiveraddressThe mTokens receiver
minAmountOutuint256The min amounts to be received

redeem

Sender redeems mTokens in exchange for the underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function redeem(uint256 redeemTokens) external checkSameChainAllowed;

Parameters

NameTypeDescription
redeemTokensuint256The number of mTokens to redeem into underlying

redeemUnderlying

Sender redeems mTokens in exchange for a specified amount of underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function redeemUnderlying(uint256 redeemAmount) external checkSameChainAllowed;

Parameters

NameTypeDescription
redeemAmountuint256The amount of underlying to redeem

borrow

Sender borrows assets from the protocol to their own address

function borrow(uint256 borrowAmount) external checkSameChainAllowed;

Parameters

NameTypeDescription
borrowAmountuint256The amount of the underlying asset to borrow

repay

Sender repays their own borrow

function repay(uint256 repayAmount) external checkSameChainAllowed returns (uint256);

Parameters

NameTypeDescription
repayAmountuint256The amount to repay, or type(uint256).max for the full outstanding amount

repayBehalf

Sender repays a borrow belonging to borrower

function repayBehalf(address borrower, uint256 repayAmount) external checkSameChainAllowed returns (uint256);

Parameters

NameTypeDescription
borroweraddressthe account with the debt being payed off
repayAmountuint256The amount to repay, or type(uint256).max for the full outstanding amount

liquidate

The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.

function liquidate(address borrower, uint256 repayAmount, address mTokenCollateral) external checkSameChainAllowed;

Parameters

NameTypeDescription
borroweraddressThe borrower of this mToken to be liquidated
repayAmountuint256The amount of the underlying borrowed asset to repay
mTokenCollateraladdressThe market in which to seize collateral from the borrower

addReserves

The sender adds to reserves.

function addReserves(uint256 addAmount) external;

Parameters

NameTypeDescription
addAmountuint256The amount fo underlying token to add as reserves

_getCashPrior

Gets balance of this contract in terms of the underlying

This excludes the value of the current message, if any

function _getCashPrior() internal view virtual override returns (uint256);

Returns

NameTypeDescription
<none>uint256The quantity of underlying tokens owned by this contract

_doTransferIn

Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. This may revert due to insufficient balance or insufficient allowance.

function _doTransferIn(address from, uint256 amount) internal virtual override returns (uint256);

_doTransferOut

Performs a transfer out, ideally returning an explanatory error code upon failure rather than reverting. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.

function _doTransferOut(address payable to, uint256 amount) internal virtual override;

Errors

mErc20_TokenNotValid

error mErc20_TokenNotValid();

mErc20Immutable

Git Source

Inherits: mErc20

Functions

constructor

Constructs the new money market

constructor(
    address underlying_,
    address operator_,
    address interestRateModel_,
    uint256 initialExchangeRateMantissa_,
    string memory name_,
    string memory symbol_,
    uint8 decimals_,
    address payable admin_
);

Parameters

NameTypeDescription
underlying_addressThe address of the underlying asset
operator_addressThe address of the Operator
interestRateModel_addressThe address of the interest rate model
initialExchangeRateMantissa_uint256The initial exchange rate, scaled by 1e18
name_stringERC-20 name of this token
symbol_stringERC-20 symbol of this token
decimals_uint8ERC-20 decimal precision of this token
admin_address payableAddress of the administrator of this token

mErc20Upgradable

Git Source

Inherits: mErc20, Initializable

Functions

constructor

Note: oz-upgrades-unsafe-allow: constructor

constructor();

_proxyInitialize

Initialize the new money market

function _proxyInitialize(
    address underlying_,
    address operator_,
    address interestRateModel_,
    uint256 initialExchangeRateMantissa_,
    string memory name_,
    string memory symbol_,
    uint8 decimals_,
    address payable admin_
) internal;

Parameters

NameTypeDescription
underlying_addressThe address of the underlying asset
operator_addressThe address of the Operator
interestRateModel_addressThe address of the interest rate model
initialExchangeRateMantissa_uint256The initial exchange rate, scaled by 1e18
name_stringERC-20 name of this token
symbol_stringERC-20 symbol of this token
decimals_uint8ERC-20 decimal precision of this token
admin_address payable

mToken

Git Source

Inherits: mTokenConfiguration, ReentrancyGuard

Functions

constructor

constructor();

_initializeMToken

Initialize the money market

function _initializeMToken(
    address operator_,
    address interestRateModel_,
    uint256 initialExchangeRateMantissa_,
    string memory name_,
    string memory symbol_,
    uint8 decimals_
) internal;

Parameters

NameTypeDescription
operator_addressThe address of the Operator
interestRateModel_addressThe address of the interest rate model
initialExchangeRateMantissa_uint256The initial exchange rate, scaled by 1e18
name_stringEIP-20 name of this token
symbol_stringEIP-20 symbol of this token
decimals_uint8EIP-20 decimal precision of this token

isMToken

function isMToken() external pure override returns (bool);

allowance

Returns the current allowance the spender has from the owner

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

Parameters

NameTypeDescription
owneraddressThe address of the token holder
spenderaddressThe address authorized to spend the tokens

Returns

NameTypeDescription
<none>uint256The current remaining number of tokens spender can spend

balanceOf

Returns the value of tokens owned by account.

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

Parameters

NameTypeDescription
owneraddress

balanceOfUnderlying

Returns the underlying asset balance of the owner

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

Parameters

NameTypeDescription
owneraddressThe address to query the balance of underlying assets for

Returns

NameTypeDescription
<none>uint256The balance of underlying assets owned by owner

getAccountSnapshot

Returns the snapshot of account details for the given account

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

Parameters

NameTypeDescription
accountaddressThe address to query the account snapshot for

Returns

NameTypeDescription
<none>uint256(token balance, borrow balance, exchange rate)
<none>uint256
<none>uint256

borrowRatePerBlock

Returns the current borrow rate per block

function borrowRatePerBlock() external view override returns (uint256);

Returns

NameTypeDescription
<none>uint256The current borrow rate per block, scaled by 1e18

supplyRatePerBlock

Returns the current supply rate per block

function supplyRatePerBlock() external view override returns (uint256);

Returns

NameTypeDescription
<none>uint256The current supply rate per block, scaled by 1e18

borrowBalanceStored

Returns the stored borrow balance for account, without accruing interest

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

Parameters

NameTypeDescription
accountaddressThe address to query the stored borrow balance for

Returns

NameTypeDescription
<none>uint256The stored borrow balance

getCash

Returns the total amount of available cash in the contract

function getCash() external view override returns (uint256);

Returns

NameTypeDescription
<none>uint256The total amount of cash

exchangeRateStored

Returns the stored exchange rate, without accruing interest

function exchangeRateStored() external view override returns (uint256);

Returns

NameTypeDescription
<none>uint256The stored exchange rate

transfer

Transfers amount tokens to the dst address

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

Parameters

NameTypeDescription
dstaddressThe address of the recipient
amountuint256The number of tokens to transfer

Returns

NameTypeDescription
<none>boolWhether the transfer was successful or not

transferFrom

Transfers amount tokens from the src address to the dst address

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

Parameters

NameTypeDescription
srcaddressThe address from which tokens are transferred
dstaddressThe address to which tokens are transferred
amountuint256The number of tokens to transfer

Returns

NameTypeDescription
<none>boolWhether the transfer was successful or not

approve

Approves spender to spend amount tokens on behalf of the caller

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

Parameters

NameTypeDescription
spenderaddressThe address authorized to spend tokens
amountuint256The number of tokens to approve

Returns

NameTypeDescription
<none>boolWhether the approval was successful or not

totalBorrowsCurrent

Returns the total amount of borrows, accounting for interest

function totalBorrowsCurrent() external override nonReentrant returns (uint256);

Returns

NameTypeDescription
<none>uint256The total amount of borrows

borrowBalanceCurrent

Returns the current borrow balance for account, accounting for interest

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

Parameters

NameTypeDescription
accountaddressThe address to query the borrow balance for

Returns

NameTypeDescription
<none>uint256The current borrow balance

exchangeRateCurrent

Returns the current exchange rate, with interest accrued

function exchangeRateCurrent() public override nonReentrant returns (uint256);

Returns

NameTypeDescription
<none>uint256The current exchange rate

seize

Transfers collateral tokens (this market) to the liquidator.

Will fail unless called by another mToken during the process of liquidation. Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.

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

Parameters

NameTypeDescription
liquidatoraddressThe account receiving seized collateral
borroweraddressThe account having collateral seized
seizeTokensuint256The number of mTokens to seize

reduceReserves

Accrues interest and reduces reserves by transferring to admin

function reduceReserves(uint256 reduceAmount) external override nonReentrant;

Parameters

NameTypeDescription
reduceAmountuint256Amount of reduction to reserves

_borrowBalanceStored

Return the borrow balance of account based on stored data

function _borrowBalanceStored(address account) internal view returns (uint256);

Parameters

NameTypeDescription
accountaddressThe address whose balance should be calculated

Returns

NameTypeDescription
<none>uint256(error code, the calculated balance or 0 if error code is non-zero)

_mint

Sender supplies assets into the market and receives mTokens in exchange

Accrues interest whether or not the operation succeeds, unless reverted

function _mint(address user, address receiver, uint256 mintAmount, uint256 minAmountOut, bool doTransfer)
    internal
    nonReentrant;

Parameters

NameTypeDescription
useraddressThe user address
receiveraddress
mintAmountuint256The amount of the underlying asset to supply
minAmountOutuint256The minimum amount to be received
doTransferboolIf an actual transfer should be performed

_redeem

Sender redeems mTokens in exchange for the underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function _redeem(address user, uint256 redeemTokens, bool doTransfer)
    internal
    nonReentrant
    returns (uint256 underlyingAmount);

Parameters

NameTypeDescription
useraddressThe user address
redeemTokensuint256The number of mTokens to redeem into underlying
doTransferboolIf an actual transfer should be performed

_redeemUnderlying

Sender redeems mTokens in exchange for a specified amount of underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function _redeemUnderlying(address user, uint256 redeemAmount, bool doTransfer) internal nonReentrant;

Parameters

NameTypeDescription
useraddressThe user address
redeemAmountuint256The amount of underlying to receive from redeeming mTokens
doTransferboolIf an actual transfer should be performed

_borrow

Sender borrows assets from the protocol to their own address

function _borrow(address user, uint256 borrowAmount, bool doTransfer) internal nonReentrant;

Parameters

NameTypeDescription
useraddressThe user address
borrowAmountuint256The amount of the underlying asset to borrow
doTransferboolIf an actual transfer should be performed

_borrowWithReceiver

Sender borrows assets from the protocol to their own address

function _borrowWithReceiver(address user, address receiver, uint256 borrowAmount) internal nonReentrant;

Parameters

NameTypeDescription
useraddressThe user address
receiveraddressThe underlying receiver address
borrowAmountuint256The amount of the underlying asset to borrow

_repay

Sender repays their own borrow

function _repay(uint256 repayAmount, bool doTransfer) internal nonReentrant returns (uint256);

Parameters

NameTypeDescription
repayAmountuint256The amount to repay, or type(uint256).max for the full outstanding amount
doTransferboolIf an actual transfer should be performed

_repayBehalf

Sender repays a borrow belonging to borrower

function _repayBehalf(address borrower, uint256 repayAmount, bool doTransfer) internal nonReentrant returns (uint256);

Parameters

NameTypeDescription
borroweraddressthe account with the debt being payed off
repayAmountuint256The amount to repay, or type(uint256).max for the full outstanding amount
doTransferboolIf an actual transfer should be performed

_liquidate

The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.

function _liquidate(
    address liquidator,
    address borrower,
    uint256 repayAmount,
    address mTokenCollateral,
    bool doTransfer
) internal nonReentrant;

Parameters

NameTypeDescription
liquidatoraddressThe liquidator address
borroweraddressThe borrower of this mToken to be liquidated
repayAmountuint256The amount of the underlying borrowed asset to repay
mTokenCollateraladdressThe market in which to seize collateral from the borrower
doTransferboolIf an actual transfer should be performed

_seize

Transfers collateral tokens (this market) to the liquidator.

Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another mToken. Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.

function _seize(address seizerToken, address liquidator, address borrower, uint256 seizeTokens) internal;

Parameters

NameTypeDescription
seizerTokenaddressThe contract seizing the collateral (i.e. borrowed mToken)
liquidatoraddressThe account receiving seized collateral
borroweraddressThe account having collateral seized
seizeTokensuint256The number of mTokens to seize

_addReserves

Accrues interest and reduces reserves by transferring from msg.sender

function _addReserves(uint256 addAmount) internal nonReentrant;

Parameters

NameTypeDescription
addAmountuint256Amount of addition to reserves

__liquidate

The liquidator liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.

function __liquidate(
    address liquidator,
    address borrower,
    uint256 repayAmount,
    address mTokenCollateral,
    bool doTransfer
) internal;

Parameters

NameTypeDescription
liquidatoraddressThe address repaying the borrow and seizing collateral
borroweraddressThe borrower of this mToken to be liquidated
repayAmountuint256The amount of the underlying borrowed asset to repay
mTokenCollateraladdressThe market in which to seize collateral from the borrower
doTransferboolIf an actual transfer should be performed

__repay

Borrows are repaid by another user (possibly the borrower).

function __repay(address payer, address borrower, uint256 repayAmount, bool doTransfer) private returns (uint256);

Parameters

NameTypeDescription
payeraddressthe account paying off the borrow
borroweraddressthe account with the debt being payed off
repayAmountuint256the amount of underlying tokens being returned, or type(uint256).max for the full outstanding amount
doTransferboolIf an actual transfer should be performed

__borrow

Users borrow assets from the protocol to their own address

function __borrow(address payable borrower, address payable receiver, uint256 borrowAmount, bool doTransfer) private;

Parameters

NameTypeDescription
borroweraddress payable
receiveraddress payable
borrowAmountuint256The amount of the underlying asset to borrow
doTransferbool

__redeem

function __redeem(address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool doTransfer)
    private
    returns (uint256 redeemAmount);

__mint

User supplies assets into the market and receives mTokens in exchange

Assumes interest has already been accrued up to the current block

function __mint(address minter, address receiver, uint256 mintAmount, uint256 minAmountOut, bool doTransfer) private;

Parameters

NameTypeDescription
minteraddressThe address of the account which is supplying the assets
receiveraddressThe address of the account which is receiving the assets
mintAmountuint256The amount of the underlying asset to supply
minAmountOutuint256The min amount to be received
doTransferboolIf an actual transfer should be performed

_transferTokens

Transfer tokens tokens from src to dst by spender

Called by both transfer and transferFrom internally

function _transferTokens(address spender, address src, address dst, uint256 tokens) private;

Parameters

NameTypeDescription
spenderaddressThe address of the account performing the transfer
srcaddressThe address of the source account
dstaddressThe address of the destination account
tokensuint256The number of tokens to transfer

mTokenConfiguration

Git Source

Inherits: mTokenStorage

Functions

onlyAdmin

modifier onlyAdmin();

setSameChainFlowState

Sets a new same chain flow state

function setSameChainFlowState(bool _newState) external onlyAdmin;

setOperator

Sets a new Operator for the market

Admin function to set a new operator

function setOperator(address _operator) external onlyAdmin;

setRolesOperator

Sets a new Operator for the market

Admin function to set a new operator

function setRolesOperator(address _roles) external onlyAdmin;

setInterestRateModel

accrues interest and updates the interest rate model using _setInterestRateModelFresh

Admin function to accrue interest and update the interest rate model

function setInterestRateModel(address newInterestRateModel) external onlyAdmin;

Parameters

NameTypeDescription
newInterestRateModeladdressthe new interest rate model to use

setBorrowRateMaxMantissa

function setBorrowRateMaxMantissa(uint256 maxMantissa) external onlyAdmin;

setReserveFactor

accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh

Admin function to accrue interest and set a new reserve factor

function setReserveFactor(uint256 newReserveFactorMantissa) external onlyAdmin;

setPendingAdmin

Begins transfer of admin rights. The newPendingAdmin must call _acceptAdmin to finalize the transfer.

Admin function to begin change of admin. The newPendingAdmin must call _acceptAdmin to finalize the transfer.

function setPendingAdmin(address payable newPendingAdmin) external onlyAdmin;

Parameters

NameTypeDescription
newPendingAdminaddress payableNew pending admin.

acceptAdmin

Accepts transfer of admin rights. msg.sender must be pendingAdmin

Admin function for pending admin to accept role and update admin

function acceptAdmin() external;

_setInterestRateModel

updates the interest rate model (*requires fresh interest accrual)

Admin function to update the interest rate model

function _setInterestRateModel(address newInterestRateModel) internal;

Parameters

NameTypeDescription
newInterestRateModeladdressthe new interest rate model to use

_setOperator

function _setOperator(address _operator) internal;

mTokenStorage

Git Source

Inherits: ImToken, ExponentialNoError

State Variables

admin

Administrator for this contract

address payable public admin;

pendingAdmin

Pending administrator for this contract

address payable public pendingAdmin;

operator

Contract which oversees inter-mToken operations

address public operator;

rolesOperator

Roles manager

IRoles public rolesOperator;

name

EIP-20 token name for this token

string public name;

symbol

EIP-20 token symbol for this token

string public symbol;

decimals

EIP-20 token decimals for this token

uint8 public decimals;

interestRateModel

Model which tells what the current interest rate should be

address public interestRateModel;

reserveFactorMantissa

Fraction of interest currently set aside for reserves

uint256 public reserveFactorMantissa;

accrualBlockTimestamp

Block timestamp that interest was last accrued at

uint256 public accrualBlockTimestamp;

borrowIndex

Accumulator of the total earned interest rate since the opening of the market

uint256 public borrowIndex;

totalBorrows

Total amount of outstanding borrows of the underlying in this market

uint256 public totalBorrows;

totalReserves

Total amount of reserves of the underlying held in this market

uint256 public totalReserves;

totalSupply

Returns the value of tokens in existence.

uint256 public totalSupply;

totalUnderlying

Returns the amount of underlying tokens

uint256 public totalUnderlying;

borrowRateMaxMantissa

Maximum borrow rate that can ever be applied

uint256 public borrowRateMaxMantissa = 0.0005e16;

sameChainFlowStateDisabled

Returns true/false for same chain flow state disable status

bool public sameChainFlowStateDisabled;

accountBorrows

mapping(address => BorrowSnapshot) internal accountBorrows;

accountTokens

mapping(address => uint256) internal accountTokens;

transferAllowances

mapping(address => mapping(address => uint256)) internal transferAllowances;

initialExchangeRateMantissa

Initial exchange rate used when minting the first mTokens (used when totalSupply = 0)

uint256 internal initialExchangeRateMantissa;

RESERVE_FACTOR_MAX_MANTISSA

Maximum fraction of interest that can be set aside for reserves

uint256 internal constant RESERVE_FACTOR_MAX_MANTISSA = 1e18;

PROTOCOL_SEIZE_SHARE_MANTISSA

Share of seized collateral that is added to reserves

uint256 internal constant PROTOCOL_SEIZE_SHARE_MANTISSA = 2.8e16;

Functions

accrueInterest

Accrues interest on the contract's outstanding loans

function accrueInterest() external virtual;

_getBlockTimestamp

Function to simply retrieve block timestamp This exists mainly for inheriting test contracts to stub this result.

function _getBlockTimestamp() internal view virtual returns (uint256);

_exchangeRateStored

Calculates the exchange rate from the underlying to the MToken

This function does not accrue interest before calculating the exchange rate Can generate issues if inflated by an attacker when market is created Solution: use 0 collateral factor initially

function _exchangeRateStored() internal view virtual returns (uint256);

Returns

NameTypeDescription
<none>uint256calculated exchange rate scaled by 1e18

_getCashPrior

Gets balance of this contract in terms of the underlying

This excludes the value of the current message, if any

function _getCashPrior() internal view virtual returns (uint256);

Returns

NameTypeDescription
<none>uint256The quantity of underlying owned by this contract

_doTransferIn

Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. This may revert due to insufficient balance or insufficient allowance.

function _doTransferIn(address from, uint256 amount) internal virtual returns (uint256);

_doTransferOut

Performs a transfer out, ideally returning an explanatory error code upon failure rather than reverting. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.

function _doTransferOut(address payable to, uint256 amount) internal virtual;

_accrueInterest

function _accrueInterest() internal;

Events

NewRolesOperator

Event emitted when rolesOperator is changed

event NewRolesOperator(address indexed oldRoles, address indexed newRoles);

NewPendingAdmin

Event emitted when pendingAdmin is changed

event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin);

NewAdmin

Event emitted when pendingAdmin is accepted, which means admin is updated

event NewAdmin(address indexed oldAdmin, address indexed newAdmin);

NewOperator

Event emitted when Operator is changed

event NewOperator(address indexed oldOperator, address indexed newOperator);

Transfer

EIP20 Transfer event

event Transfer(address indexed from, address indexed to, uint256 amount);

Approval

EIP20 Approval event

event Approval(address indexed owner, address indexed spender, uint256 amount);

AccrueInterest

Event emitted when interest is accrued

event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);

Mint

Event emitted when tokens are minted

event Mint(address indexed minter, address indexed receiver, uint256 mintAmount, uint256 mintTokens);

Redeem

Event emitted when tokens are redeemed

event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);

Borrow

Event emitted when underlying is borrowed

event Borrow(address indexed borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);

RepayBorrow

Event emitted when a borrow is repaid

event RepayBorrow(
    address indexed payer, address indexed borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows
);

LiquidateBorrow

Event emitted when a borrow is liquidated

event LiquidateBorrow(
    address indexed liquidator,
    address indexed borrower,
    uint256 repayAmount,
    address indexed mTokenCollateral,
    uint256 seizeTokens
);

NewMarketInterestRateModel

Event emitted when interestRateModel is changed

event NewMarketInterestRateModel(address indexed oldInterestRateModel, address indexed newInterestRateModel);

NewReserveFactor

Event emitted when the reserve factor is changed

event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);

ReservesAdded

Event emitted when the reserves are added

event ReservesAdded(address indexed benefactor, uint256 addAmount, uint256 newTotalReserves);

ReservesReduced

Event emitted when the reserves are reduced

event ReservesReduced(address indexed admin, uint256 reduceAmount, uint256 newTotalReserves);

NewBorrowRateMaxMantissa

Event emitted when the borrow max mantissa is updated

event NewBorrowRateMaxMantissa(uint256 oldVal, uint256 maxMantissa);

SameChainFlowStateUpdated

Event emitted when same chain flow state is enabled or disabled

event SameChainFlowStateUpdated(address indexed sender, bool _oldState, bool _newState);

ZkVerifierUpdated

Event emitted when same chain flow state is enabled or disabled

event ZkVerifierUpdated(address indexed oldVerifier, address indexed newVerifier);

Errors

mToken_OnlyAdmin

error mToken_OnlyAdmin();

mToken_RedeemEmpty

error mToken_RedeemEmpty();

mToken_InvalidInput

error mToken_InvalidInput();

mToken_OnlyAdminOrRole

error mToken_OnlyAdminOrRole();

mToken_TransferNotValid

error mToken_TransferNotValid();

mToken_MinAmountNotValid

error mToken_MinAmountNotValid();

mToken_BorrowRateTooHigh

error mToken_BorrowRateTooHigh();

mToken_AlreadyInitialized

error mToken_AlreadyInitialized();

mToken_ReserveFactorTooHigh

error mToken_ReserveFactorTooHigh();

mToken_ExchangeRateNotValid

error mToken_ExchangeRateNotValid();

mToken_MarketMethodNotValid

error mToken_MarketMethodNotValid();

mToken_LiquidateSeizeTooMuch

error mToken_LiquidateSeizeTooMuch();

mToken_RedeemCashNotAvailable

error mToken_RedeemCashNotAvailable();

mToken_BorrowCashNotAvailable

error mToken_BorrowCashNotAvailable();

mToken_ReserveCashNotAvailable

error mToken_ReserveCashNotAvailable();

mToken_RedeemTransferOutNotPossible

error mToken_RedeemTransferOutNotPossible();

mToken_SameChainOperationsAreDisabled

error mToken_SameChainOperationsAreDisabled();

mToken_CollateralBlockTimestampNotValid

error mToken_CollateralBlockTimestampNotValid();

Structs

BorrowSnapshot

Container for borrow balance information

struct BorrowSnapshot {
    uint256 principal;
    uint256 interestIndex;
}

Contents

IMendiMarket

Git Source

Functions

repayBorrow

function repayBorrow(uint256 repayAmount) external returns (uint256);

repayBorrowBehalf

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

redeemUnderlying

function redeemUnderlying(uint256 redeemAmount) external returns (uint256);

redeem

function redeem(uint256 amount) external returns (uint256);

underlying

function underlying() external view returns (address);

balanceOf

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

balanceOfUnderlying

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

borrowBalanceStored

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

IMendiComptroller

Git Source

Functions

getAssetsIn

function getAssetsIn(address account) external view returns (IMendiMarket[] memory);

Migrator

Git Source

Functions

getAllCollateralMarkets

Get all markets where params.userV1 has collateral in on Mendi

function getAllCollateralMarkets(MigrationParams calldata params) external view returns (address[] memory markets);

Parameters

NameTypeDescription
paramsMigrationParamsMigration parameters containing protocol addresses

getAllPositions

Get all migratable positions from Mendi to Malda

function getAllPositions(MigrationParams calldata params) external returns (Position[] memory positions);

Parameters

NameTypeDescription
paramsMigrationParamsMigration parameters containing protocol addresses

migrateAllPositions

Migrates all positions from Mendi to Malda

function migrateAllPositions(MigrationParams calldata params) external;

Parameters

NameTypeDescription
paramsMigrationParamsMigration parameters containing protocol addresses

_collectMendiPositions

Collects all user positions from Mendi

function _collectMendiPositions(MigrationParams memory params) private returns (Position[] memory);

_getMaldaMarket

Gets corresponding Malda market for a given underlying

function _getMaldaMarket(address maldaOperator, address underlying) private view returns (address);

Structs

MigrationParams

struct MigrationParams {
    address mendiComptroller;
    address maldaOperator;
    address userV1;
    address userV2;
}

Position

struct Position {
    address mendiMarket;
    address maldaMarket;
    uint256 collateralUnderlyingAmount;
    uint256 borrowAmount;
}

Contents

MaldaNft

Git Source

Inherits: ERC721Enumerable, Ownable

State Variables

merkleRoot

bytes32 public merkleRoot;

hasClaimed

mapping(address => mapping(uint256 => bool)) public hasClaimed;

minted

mapping(uint256 => bool) public minted;

_nextTokenId

uint256 private _nextTokenId;

_baseTokenURI

string private _baseTokenURI;

Functions

constructor

constructor(string memory name, string memory symbol, string memory baseURI, address owner)
    ERC721(name, symbol)
    Ownable(owner);

mint

function mint(address to, uint256 tokenId) external onlyOwner;

setBaseURI

function setBaseURI(string memory baseURI) external onlyOwner;

setMerkleRoot

function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner;

canClaim

function canClaim(address claimer, uint256 tokenId, bytes32[] calldata merkleProof) external view returns (bool);

claim

function claim(uint256 tokenId, bytes32[] calldata merkleProof) external;

transferFrom

non-transferable

function transferFrom(address, address, uint256) public override(ERC721, IERC721);

safeTransferFrom

non-transferable

function safeTransferFrom(address, address, uint256, bytes memory) public override(ERC721, IERC721);

_baseURI

function _baseURI() internal view override returns (string memory);

Events

MerkleRootSet

event MerkleRootSet(bytes32 merkleRoot);

TokensClaimed

event TokensClaimed(address indexed claimer, uint256 indexed tokenIdClaimed);

Errors

MaldaNft_MerkleRootNotSet

error MaldaNft_MerkleRootNotSet();

MaldaNft_InvalidMerkleProof

error MaldaNft_InvalidMerkleProof();

MaldaNft_TokenAlreadyMinted

error MaldaNft_TokenAlreadyMinted();

MaldaNft_TokenAlreadyClaimed

error MaldaNft_TokenAlreadyClaimed();

MaldaNft_TokenNotTransferable

error MaldaNft_TokenNotTransferable();

Contents

ChainlinkOracle

Git Source

Inherits: IOracleOperator

State Variables

priceFeeds

mapping(string => IAggregatorV3) public priceFeeds;

baseUnits

mapping(string => uint256) public baseUnits;

DECIMALS

uint8 public constant DECIMALS = 18;

Functions

constructor

constructor(string[] memory symbols_, IAggregatorV3[] memory feeds_, uint256[] memory baseUnits_);

getPrice

Get the price of a mToken asset

function getPrice(address mToken) external view override returns (uint256);

Parameters

NameTypeDescription
mTokenaddressThe mToken to get the price of

Returns

NameTypeDescription
<none>uint256The underlying asset price mantissa (scaled by 1e18). Zero means the price is unavailable.

getUnderlyingPrice

Get the underlying price of a mToken asset

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

Parameters

NameTypeDescription
mTokenaddressThe mToken to get the underlying price of

Returns

NameTypeDescription
<none>uint256The underlying asset price mantissa (scaled by 1e18). Zero means the price is unavailable.

_getLatestPrice

function _getLatestPrice(string memory symbol) internal view returns (uint256, uint256);

Errors

ChainlinkOracle_NoPriceFeed

error ChainlinkOracle_NoPriceFeed();

ChainlinkOracle_ZeroPrice

error ChainlinkOracle_ZeroPrice();

MixedPriceOracleV3

Git Source

Inherits: IOracleOperator

State Variables

STALENESS_PERIOD

uint256 public immutable STALENESS_PERIOD;

configs

mapping(string => IDefaultAdapter.PriceConfig) public configs;

stalenessPerSymbol

mapping(string => uint256) public stalenessPerSymbol;

roles

IRoles public immutable roles;

Functions

constructor

constructor(
    string[] memory symbols_,
    IDefaultAdapter.PriceConfig[] memory configs_,
    address roles_,
    uint256 stalenessPeriod_
);

setStaleness

function setStaleness(string memory symbol, uint256 val) external;

setConfig

function setConfig(string memory symbol, IDefaultAdapter.PriceConfig memory config) external;

getPrice

function getPrice(address mToken) public view returns (uint256);

getUnderlyingPrice

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

_getPriceUSD

function _getPriceUSD(string memory symbol) internal view returns (uint256);

_getLatestPrice

function _getLatestPrice(string memory symbol, IDefaultAdapter.PriceConfig memory config)
    internal
    view
    returns (uint256, uint256);

_getStaleness

function _getStaleness(string memory symbol) internal view returns (uint256);

Events

ConfigSet

event ConfigSet(string symbol, IDefaultAdapter.PriceConfig config);

StalenessUpdated

event StalenessUpdated(string symbol, uint256 val);

Errors

MixedPriceOracle_Unauthorized

error MixedPriceOracle_Unauthorized();

MixedPriceOracle_StalePrice

error MixedPriceOracle_StalePrice();

MixedPriceOracle_InvalidPrice

error MixedPriceOracle_InvalidPrice();

MixedPriceOracle_InvalidRound

error MixedPriceOracle_InvalidRound();

MixedPriceOracle_InvalidConfig

error MixedPriceOracle_InvalidConfig();

MixedPriceOracleV4

Git Source

Inherits: IOracleOperator

State Variables

STALENESS_PERIOD

uint256 public immutable STALENESS_PERIOD;

configs

mapping(string => PriceConfig) public configs;

stalenessPerSymbol

mapping(string => uint256) public stalenessPerSymbol;

deltaPerSymbol

mapping(string => uint256) public deltaPerSymbol;

maxPriceDelta

uint256 public maxPriceDelta = 1.5e3;

PRICE_DELTA_EXP

uint256 public constant PRICE_DELTA_EXP = 1e5;

roles

IRoles public immutable roles;

Functions

constructor

constructor(string[] memory symbols_, PriceConfig[] memory configs_, address roles_, uint256 stalenessPeriod_);

setStaleness

function setStaleness(string memory symbol, uint256 val) external;

setConfig

function setConfig(string memory symbol, PriceConfig memory config) external;

setMaxPriceDelta

function setMaxPriceDelta(uint256 _delta) external;

setSymbolMaxPriceDelta

function setSymbolMaxPriceDelta(uint256 _delta, string calldata _symbol) external;

getPrice

function getPrice(address mToken) public view returns (uint256);

getUnderlyingPrice

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

_getPriceUSD

function _getPriceUSD(string memory symbol) internal view returns (uint256);

_getLatestPrice

function _getLatestPrice(string memory symbol, PriceConfig memory config) internal view returns (uint256, uint256);

_absDiff

function _absDiff(int256 a, int256 b) internal pure returns (uint256);

_getStaleness

function _getStaleness(string memory symbol) internal view returns (uint256);

Events

ConfigSet

event ConfigSet(string symbol, PriceConfig config);

StalenessUpdated

event StalenessUpdated(string symbol, uint256 val);

PriceDeltaUpdated

event PriceDeltaUpdated(uint256 oldVal, uint256 newVal);

PriceSymbolDeltaUpdated

event PriceSymbolDeltaUpdated(uint256 oldVal, uint256 newVal, string symbol);

Errors

MixedPriceOracle_Unauthorized

error MixedPriceOracle_Unauthorized();

MixedPriceOracle_ApiV3StalePrice

error MixedPriceOracle_ApiV3StalePrice();

MixedPriceOracle_eOracleStalePrice

error MixedPriceOracle_eOracleStalePrice();

MixedPriceOracle_InvalidPrice

error MixedPriceOracle_InvalidPrice();

MixedPriceOracle_InvalidRound

error MixedPriceOracle_InvalidRound();

MixedPriceOracle_InvalidConfig

error MixedPriceOracle_InvalidConfig();

MixedPriceOracle_InvalidConfigDecimals

error MixedPriceOracle_InvalidConfigDecimals();

MixedPriceOracle_DeltaTooHigh

error MixedPriceOracle_DeltaTooHigh();

MixedPriceOracle_MissingFeed

error MixedPriceOracle_MissingFeed();

Structs

PriceConfig

struct PriceConfig {
    address api3Feed;
    address eOracleFeed;
    string toSymbol;
    uint256 underlyingDecimals;
}

Contents

Pauser

Git Source

Inherits: Ownable, IPauser

State Variables

roles

IRoles public immutable roles;

operator

IOperator public immutable operator;

pausableContracts

PausableContract[] public pausableContracts;

registeredContracts

mapping(address _contract => bool _registered) public registeredContracts;

contractTypes

mapping(address _contract => PausableType _type) public contractTypes;

Functions

constructor

constructor(address _roles, address _operator, address _owner) Ownable(_owner);

addPausableMarket

add pauable contract

function addPausableMarket(address _contract, PausableType _contractType) external onlyOwner;

Parameters

NameTypeDescription
_contractaddressthe pausable contract
_contractTypePausableTypethe pausable contract type

removePausableMarket

removes pauable contract

function removePausableMarket(address _contract) external onlyOwner;

Parameters

NameTypeDescription
_contractaddressthe pausable contract

emergencyPauseMarket

pauses all operations for a market

function emergencyPauseMarket(address _market) external;

Parameters

NameTypeDescription
_marketaddressthe mToken address

emergencyPauseMarketFor

pauses a specific operation for a market

function emergencyPauseMarketFor(address _market, ImTokenOperationTypes.OperationType _pauseType) external;

Parameters

NameTypeDescription
_marketaddressthe mToken address
_pauseTypeImTokenOperationTypes.OperationTypethe operation type

emergencyPauseAll

pauses all operations for all registered markets

function emergencyPauseAll() external;

_pauseAllMarketOperations

function _pauseAllMarketOperations(address _market) private;

_pauseMarketOperation

function _pauseMarketOperation(address _market, ImTokenOperationTypes.OperationType _pauseType) private;

_pause

function _pause(address _market, ImTokenOperationTypes.OperationType _pauseType) private;

_findIndex

function _findIndex(address _address) private view returns (uint256);

Contents

Contents

AccrossBridge

Git Source

Inherits: BaseBridge, IBridge, ReentrancyGuard

State Variables

acrossSpokePool

address public immutable acrossSpokePool;

maxSlippage

uint256 public immutable maxSlippage;

whitelistedRelayers

mapping(uint32 => mapping(address => bool)) public whitelistedRelayers;

SLIPPAGE_PRECISION

uint256 private constant SLIPPAGE_PRECISION = 1e5;

Functions

constructor

constructor(address _roles, address _spokePool) BaseBridge(_roles);

onlySpokePool

modifier onlySpokePool();

setWhitelistedRelayer

Whitelists a delegate address

function setWhitelistedRelayer(uint32 _dstId, address _relayer, bool status) external onlyBridgeConfigurator;

getFee

computes fee for bridge operation

function getFee(uint32, bytes memory, bytes memory) external pure returns (uint256);

Parameters

NameTypeDescription
<none>uint32
<none>bytes
<none>bytes

isRelayerWhitelisted

returns if an address represents a whitelisted delegates

function isRelayerWhitelisted(uint32 dstChain, address relayer) external view returns (bool);

sendMsg

rebalance through bridge

function sendMsg(
    uint256 _extractedAmount,
    address _market,
    uint32 _dstChainId,
    address _token,
    bytes memory _message,
    bytes memory
) external payable onlyRebalancer;

Parameters

NameTypeDescription
_extractedAmountuint256extracted amount for rebalancing
_marketaddressdestination address
_dstChainIduint32destination chain id
_tokenaddressthe token to rebalance
_messagebytesoperation message data
<none>bytes

handleV3AcrossMessage

handles AcrossV3 SpokePool message

function handleV3AcrossMessage(address tokenSent, uint256 amount, address, bytes memory message)
    external
    onlySpokePool
    nonReentrant;

Parameters

NameTypeDescription
tokenSentaddressthe token address received
amountuint256the token amount
<none>address
messagebytesthe custom message sent from source

_decodeMessage

function _decodeMessage(bytes memory _message) private pure returns (DecodedMessage memory);

_depositV3Now

function _depositV3Now(bytes memory _message, address _token, uint32 _dstChainId, address _market) private;

Events

Rebalanced

event Rebalanced(address indexed market, uint256 amount);

WhitelistedRelayerStatusUpdated

event WhitelistedRelayerStatusUpdated(
    address indexed sender, uint32 indexed dstId, address indexed delegate, bool status
);

Errors

AcrossBridge_TokenMismatch

error AcrossBridge_TokenMismatch();

AcrossBridge_NotAuthorized

error AcrossBridge_NotAuthorized();

AcrossBridge_NotImplemented

error AcrossBridge_NotImplemented();

AcrossBridge_AddressNotValid

error AcrossBridge_AddressNotValid();

AcrossBridge_SlippageNotValid

error AcrossBridge_SlippageNotValid();

AcrossBridge_RelayerNotValid

error AcrossBridge_RelayerNotValid();

Structs

DecodedMessage

struct DecodedMessage {
    uint256 inputAmount;
    uint256 outputAmount;
    address relayer;
    uint32 deadline;
    uint32 exclusivityDeadline;
}

BaseBridge

Git Source

State Variables

roles

IRoles public roles;

Functions

constructor

constructor(address _roles);

onlyBridgeConfigurator

modifier onlyBridgeConfigurator();

onlyRebalancer

modifier onlyRebalancer();

Errors

BaseBridge_NotAuthorized

error BaseBridge_NotAuthorized();

BaseBridge_AmountMismatch

error BaseBridge_AmountMismatch();

BaseBridge_AmountNotValid

error BaseBridge_AmountNotValid();

BaseBridge_AddressNotValid

error BaseBridge_AddressNotValid();

ConnextBridge

Git Source

Inherits: BaseBridge, IBridge

State Variables

connext

IConnext public immutable connext;

domainIds

mapping(uint32 => uint32) public domainIds;

whitelistedDelegates

mapping(uint32 => mapping(address => bool)) public whitelistedDelegates;

Functions

constructor

constructor(address _roles, address _connext) BaseBridge(_roles);

setDomainId

Set domain id

function setDomainId(uint32 _dstId, uint32 _domainId) external onlyBridgeConfigurator;

setWhitelistedDelegate

Whitelists a delegate address

function setWhitelistedDelegate(uint32 _dstId, address _delegate, bool status) external onlyBridgeConfigurator;

getFee

computes fee for bridge operation

function getFee(uint32, bytes memory, bytes memory) external pure returns (uint256);

Parameters

NameTypeDescription
<none>uint32
<none>bytes
<none>bytes

isDelegateWhitelisted

returns if an address represents a whitelisted delegates

function isDelegateWhitelisted(uint32 dstChain, address delegate) external view returns (bool);

sendMsg

rebalance through bridge

function sendMsg(
    uint256 _extractedAmount,
    address _market,
    uint32 _dstChainId,
    address _token,
    bytes memory _message,
    bytes memory
) external payable onlyRebalancer;

Parameters

NameTypeDescription
_extractedAmountuint256extracted amount for rebalancing
_marketaddressdestination address
_dstChainIduint32destination chain id
_tokenaddressthe token to rebalance
_messagebytesoperation message data
<none>bytes

_decodeMessage

function _decodeMessage(bytes memory _message) private pure returns (DecodedMessage memory);

Events

MsgSent

event MsgSent(uint256 indexed dstChainId, address indexed market, uint256 amountLD, uint256 slippage, bytes32 id);

DomainIdSet

event DomainIdSet(uint32 indexed dstId, uint32 indexed domainId);

WhitelistedDelegateStatusUpdated

event WhitelistedDelegateStatusUpdated(
    address indexed sender, uint32 indexed dstId, address indexed delegate, bool status
);

Errors

Connext_NotEnoughFees

error Connext_NotEnoughFees();

Connext_NotImplemented

error Connext_NotImplemented();

Connext_DomainIdNotSet

error Connext_DomainIdNotSet();

Connext_DelegateNotValid

error Connext_DelegateNotValid();

Structs

DecodedMessage

struct DecodedMessage {
    address delegate;
    uint256 amount;
    uint256 slippage;
    uint256 relayerFee;
}

EverclearBridge

Git Source

Inherits: BaseBridge, IBridge

State Variables

everclearSpoke

IEverclearSpoke public everclearSpoke;

Functions

constructor

constructor(address _roles, address _spoke) BaseBridge(_roles);

getFee

computes fee for bridge operation

function getFee(uint32, bytes memory, bytes memory) external pure returns (uint256);

Parameters

NameTypeDescription
<none>uint32
<none>bytes
<none>bytes

sendMsg

rebalance through bridge

function sendMsg(
    uint256 _extractedAmount,
    address _market,
    uint32 _dstChainId,
    address _token,
    bytes memory _message,
    bytes memory
) external payable onlyRebalancer;

Parameters

NameTypeDescription
_extractedAmountuint256extracted amount for rebalancing
_marketaddressdestination address
_dstChainIduint32destination chain id
_tokenaddressthe token to rebalance
_messagebytesoperation message data
<none>bytes

Events

MsgSent

event MsgSent(uint256 indexed dstChainId, address indexed market, uint256 amountLD, bytes32 id);

Errors

Everclear_NotImplemented

error Everclear_NotImplemented();

Everclear_AddressNotValid

error Everclear_AddressNotValid();

LZBridge

Git Source

Inherits: BaseBridge, IBridge

Functions

constructor

constructor(address _roles) BaseBridge(_roles);

getFee

computes fee for bridge operation

use getOptionsData for _bridgeData

function getFee(uint32 _dstChainId, bytes memory _message, bytes memory _composeMsg) external view returns (uint256);

Parameters

NameTypeDescription
_dstChainIduint32destination chain id
_messagebytesoperation message data
_composeMsgbytes

sendMsg

rebalance through bridge

function sendMsg(
    uint256 _extractedAmount,
    address _market,
    uint32 _dstChainId,
    address _token,
    bytes memory _message,
    bytes memory _composeMsg
) external payable onlyRebalancer;

Parameters

NameTypeDescription
_extractedAmountuint256extracted amount for rebalancing
_marketaddressdestination address
_dstChainIduint32destination chain id
_tokenaddressthe token to rebalance
_messagebytesoperation message data
_composeMsgbytes

_getFee

function _getFee(uint32 dstEid, bytes memory _message, bytes memory _composeMsg)
    private
    view
    returns (MessagingFee memory fees, SendParam memory lzSendParams);

Events

MsgSent

event MsgSent(uint32 indexed dstChainId, address indexed market, uint256 amountLD, uint256 minAmountLD, bytes32 guid);

Errors

LZBridge_NotEnoughFees

error LZBridge_NotEnoughFees();

LZBridge_ChainNotRegistered

error LZBridge_ChainNotRegistered();

LZBridge_DestinationMismatch

error LZBridge_DestinationMismatch();

Rebalancer

Git Source

Inherits: IRebalancer

State Variables

roles

IRoles public roles;

nonce

uint256 public nonce;

logs

mapping(uint32 => mapping(uint256 => Msg)) public logs;

whitelistedBridges

mapping(address => bool) public whitelistedBridges;

whitelistedDestinations

mapping(uint32 => bool) public whitelistedDestinations;

allowedList

mapping(address => bool) public allowedList;

saveAddress

address public saveAddress;

maxTransferSizes

mapping(uint32 => mapping(address => uint256)) public maxTransferSizes;

minTransferSizes

mapping(uint32 => mapping(address => uint256)) public minTransferSizes;

currentTransferSize

mapping(uint32 => mapping(address => TransferInfo)) public currentTransferSize;

transferTimeWindow

uint256 public transferTimeWindow;

Functions

constructor

constructor(address _roles, address _saveAddress);

setAllowList

function setAllowList(address[] calldata list, bool status) external;

setWhitelistedBridgeStatus

function setWhitelistedBridgeStatus(address _bridge, bool _status) external;

setWhitelistedDestination

function setWhitelistedDestination(uint32 _dstId, bool _status) external;

saveEth

function saveEth() external;

setMinTransferSize

function setMinTransferSize(uint32 _dstChainId, address _token, uint256 _limit) external;

setMaxTransferSize

function setMaxTransferSize(uint32 _dstChainId, address _token, uint256 _limit) external;

isBridgeWhitelisted

returns if a bridge implementation is whitelisted

function isBridgeWhitelisted(address bridge) external view returns (bool);

isDestinationWhitelisted

returns if a destination is whitelisted

function isDestinationWhitelisted(uint32 dstId) external view returns (bool);

sendMsg

sends a bridge message

function sendMsg(address _bridge, address _market, uint256 _amount, Msg calldata _msg) external payable;

Parameters

NameTypeDescription
_bridgeaddress
_marketaddressthe market to rebalance from address
_amountuint256the amount to rebalance
_msgMsg

Structs

TransferInfo

struct TransferInfo {
    uint256 size;
    uint256 timestamp;
}

Contents

ReferralSigning

Git Source

State Variables

referredByRegistry

mapping(address referredBy => mapping(address user => bool wasReferred)) public referredByRegistry;

referralsForUserRegistry

mapping(address user => address referredBy) public referralsForUserRegistry;

referralRegistry

mapping(address referredBy => address[] users) public referralRegistry;

totalReferred

mapping(address referredBy => uint256 total) public totalReferred;

isUserReferred

mapping(address user => bool wasReferred) public isUserReferred;

nonces

mapping(address user => uint256 nonce) public nonces;

Functions

onlyNewUser

modifier onlyNewUser();

claimReferral

function claimReferral(bytes calldata signature, address referrer) external onlyNewUser;

Events

ReferralClaimed

event ReferralClaimed(address indexed referred, address indexed referrer);

ReferralRejected

event ReferralRejected(address indexed referred, address indexed referrer, string reason);

Errors

ReferralSigning_SameUser

error ReferralSigning_SameUser();

ReferralSigning_InvalidSignature

error ReferralSigning_InvalidSignature();

ReferralSigning_UserAlreadyReferred

error ReferralSigning_UserAlreadyReferred();

ReferralSigning_ContractReferrerNotAllowed

error ReferralSigning_ContractReferrerNotAllowed();

Contents

RewardDistributor

Git Source

Inherits: IRewardDistributor, ExponentialNoError, Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable

State Variables

REWARD_INITIAL_INDEX

uint224 public constant REWARD_INITIAL_INDEX = 1e36;

operator

The operator that rewards are distributed to

address public operator;

rewardMarketState

The Reward state for each reward token for each market

mapping(address => mapping(address => IRewardDistributorData.RewardMarketState)) public rewardMarketState;

rewardAccountState

The Reward state for each reward token for each account

mapping(address => mapping(address => IRewardDistributorData.RewardAccountState)) public rewardAccountState;

rewardTokens

Added reward tokens

address[] public rewardTokens;

isRewardToken

Flag to check if reward token added before

mapping(address => bool) public isRewardToken;

Functions

onlyOperator

modifier onlyOperator();

constructor

Note: oz-upgrades-unsafe-allow: constructor

constructor();

claim

function claim(address[] memory holders) public override nonReentrant;

getBlockTimestamp

Get block timestamp

function getBlockTimestamp() public view override returns (uint32);

getRewardTokens

Added reward tokens

function getRewardTokens() public view override returns (address[] memory);

initialize

function initialize(address _owner) public initializer;

setOperator

function setOperator(address _operator) external onlyOwner;

whitelistToken

function whitelistToken(address rewardToken_) public onlyOwner;

updateRewardSpeeds

function updateRewardSpeeds(
    address rewardToken_,
    address[] memory mTokens,
    uint256[] memory supplySpeeds,
    uint256[] memory borrowSpeeds
) public onlyOwner;

grantReward

function grantReward(address token, address user, uint256 amount) public onlyOwner;

notifySupplyIndex

Notifies supply index

function notifySupplyIndex(address mToken) external override onlyOperator;

notifyBorrowIndex

Notifies borrow index

function notifyBorrowIndex(address mToken) external override onlyOperator;

notifySupplier

Notifies supplier

function notifySupplier(address mToken, address supplier) external override onlyOperator;

notifyBorrower

Notifies borrower

function notifyBorrower(address mToken, address borrower) external override onlyOperator;

_updateRewardSpeed

function _updateRewardSpeed(address rewardToken, address mToken, uint256 supplySpeed, uint256 borrowSpeed) private;

_notifySupplyIndex

function _notifySupplyIndex(address rewardToken, address mToken) private;

_notifyBorrowIndex

function _notifyBorrowIndex(address rewardToken, address mToken) private;

_notifySupplier

function _notifySupplier(address rewardToken, address mToken, address supplier) private;

_notifyBorrower

function _notifyBorrower(address rewardToken, address mToken, address borrower) private;

_claim

function _claim(address rewardToken, address[] memory holders) internal;

_grantReward

function _grantReward(address token, address user, uint256 amount) internal returns (uint256);

Errors

RewardDistributor_OnlyOperator

error RewardDistributor_OnlyOperator();

RewardDistributor_TransferFailed

error RewardDistributor_TransferFailed();

RewardDistributor_RewardNotValid

error RewardDistributor_RewardNotValid();

RewardDistributor_AddressNotValid

error RewardDistributor_AddressNotValid();

RewardDistributor_AddressAlreadyRegistered

error RewardDistributor_AddressAlreadyRegistered();

RewardDistributor_SupplySpeedArrayLengthMismatch

error RewardDistributor_SupplySpeedArrayLengthMismatch();

RewardDistributor_BorrowSpeedArrayLengthMismatch

error RewardDistributor_BorrowSpeedArrayLengthMismatch();

Contents

Deployer

Git Source

State Variables

admin

address public admin;

pendingAdmin

address public pendingAdmin;

Functions

onlyAdmin

modifier onlyAdmin();

constructor

constructor(address _admin);

receive

receive() external payable;

setPendingAdmin

function setPendingAdmin(address newAdmin) external onlyAdmin;

saveEth

function saveEth() external;

setNewAdmin

function setNewAdmin(address _addr) external;

precompute

function precompute(bytes32 salt) external view returns (address);

create

function create(bytes32 salt, bytes memory code) external payable onlyAdmin returns (address);

acceptAdmin

function acceptAdmin() external;

Events

AdminSet

event AdminSet(address indexed _admin);

PendingAdminSet

event PendingAdminSet(address indexed _admin);

AdminAccepted

event AdminAccepted(address indexed _admin);

Errors

NotAuthorized

error NotAuthorized(address admin, address sender);

ExponentialNoError

Git Source

Author: Compound

Exp is a struct which stores decimals with a fixed precision of 18 decimal places. Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: Exp({mantissa: 5100000000000000000}).

State Variables

expScale

uint256 constant expScale = 1e18;

doubleScale

uint256 constant doubleScale = 1e36;

halfExpScale

uint256 constant halfExpScale = expScale / 2;

mantissaOne

uint256 constant mantissaOne = expScale;

Functions

truncate

Truncates the given exp to a whole number value. For example, truncate(Exp{mantissa: 15 * expScale}) = 15

function truncate(Exp memory exp) internal pure returns (uint256);

mul_ScalarTruncate

Multiply an Exp by a scalar, then truncate to return an unsigned integer.

function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256);

mul_ScalarTruncateAddUInt

Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.

function mul_ScalarTruncateAddUInt(Exp memory a, uint256 scalar, uint256 addend) internal pure returns (uint256);

lessThanExp

Checks if first Exp is less than second Exp.

function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool);

lessThanOrEqualExp

Checks if left Exp <= right Exp.

function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool);

greaterThanExp

Checks if left Exp > right Exp.

function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool);

isZeroExp

returns true if Exp is exactly zero

function isZeroExp(Exp memory value) internal pure returns (bool);

safe224

function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224);

safe32

function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32);

add_

function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory);

add_

function add_(Double memory a, Double memory b) internal pure returns (Double memory);

add_

function add_(uint256 a, uint256 b) internal pure returns (uint256);

sub_

function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory);

sub_

function sub_(Double memory a, Double memory b) internal pure returns (Double memory);

sub_

function sub_(uint256 a, uint256 b) internal pure returns (uint256);

mul_

function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory);

mul_

function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory);

mul_

function mul_(uint256 a, Exp memory b) internal pure returns (uint256);

mul_

function mul_(Double memory a, Double memory b) internal pure returns (Double memory);

mul_

function mul_(Double memory a, uint256 b) internal pure returns (Double memory);

mul_

function mul_(uint256 a, Double memory b) internal pure returns (uint256);

mul_

function mul_(uint256 a, uint256 b) internal pure returns (uint256);

div_

function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory);

div_

function div_(Exp memory a, uint256 b) internal pure returns (Exp memory);

div_

function div_(uint256 a, Exp memory b) internal pure returns (uint256);

div_

function div_(Double memory a, Double memory b) internal pure returns (Double memory);

div_

function div_(Double memory a, uint256 b) internal pure returns (Double memory);

div_

function div_(uint256 a, Double memory b) internal pure returns (uint256);

div_

function div_(uint256 a, uint256 b) internal pure returns (uint256);

fraction

function fraction(uint256 a, uint256 b) internal pure returns (Double memory);

Structs

Exp

struct Exp {
    uint256 mantissa;
}

Double

struct Double {
    uint256 mantissa;
}

LiquidationHelper

Git Source

Functions

getBorrowerPosition

function getBorrowerPosition(address borrower, address market)
    external
    view
    returns (bool shouldLiquidate, uint256 repayAmount);

IWrappedNative

Git Source

Functions

deposit

function deposit() external payable;

transfer

function transfer(address to, uint256 value) external returns (bool);

withdraw

function withdraw(uint256) external;

WrapAndSupply

Git Source

State Variables

wrappedNative

IWrappedNative public immutable wrappedNative;

Functions

constructor

constructor(address _wrappedNative);

wrapAndSupplyOnHostMarket

Wraps a native coin into its wrapped version and supplies on a host market

function wrapAndSupplyOnHostMarket(address mToken, address receiver, uint256 minAmount) external payable;

Parameters

NameTypeDescription
mTokenaddressThe market address
receiveraddressThe mToken receiver
minAmountuint256

wrapAndSupplyOnExtensionMarket

Wraps a native coin into its wrapped version and supplies on an extension market

function wrapAndSupplyOnExtensionMarket(address mTokenGateway, address receiver, bytes4 selector) external payable;

Parameters

NameTypeDescription
mTokenGatewayaddressThe market address
receiveraddressThe receiver
selectorbytes4The host chain function selector

_wrap

function _wrap() private returns (uint256);

Events

WrappedAndSupplied

event WrappedAndSupplied(address indexed sender, address indexed receiver, address indexed market, uint256 amount);

Errors

WrapAndSupply_AddressNotValid

error WrapAndSupply_AddressNotValid();

WrapAndSupply_AmountNotValid

error WrapAndSupply_AmountNotValid();

Contents

IZkVerifier

Git Source

Functions

verifyInput

function verifyInput(bytes calldata journalEntry, bytes calldata seal) external view;

ZkVerifier

Git Source

Inherits: Ownable, IZkVerifier

State Variables

verifier

IRiscZeroVerifier public verifier;

imageId

bytes32 public imageId;

Functions

constructor

constructor(address _owner, bytes32 _imageId, address _verifier) Ownable(_owner);

setVerifier

Sets the _risc0Verifier address

Admin check is needed on the external method

function setVerifier(address _risc0Verifier) external onlyOwner;

Parameters

NameTypeDescription
_risc0Verifieraddressthe new IRiscZeroVerifier address

setImageId

Sets the image id

Admin check is needed on the external method

function setImageId(bytes32 _imageId) external onlyOwner;

Parameters

NameTypeDescription
_imageIdbytes32the new image id

verifyInput

Verifies an input

function verifyInput(bytes calldata journalEntry, bytes calldata seal) external view;

Parameters

NameTypeDescription
journalEntrybytesthe risc0 journal entry
sealbytesthe risc0 seal

_checkAddresses

function _checkAddresses() private view;

__verify

function __verify(bytes calldata journalEntry, bytes calldata seal) private view;

Events

ImageSet

event ImageSet(bytes32 _imageId);

VerifierSet

event VerifierSet(address indexed oldVerifier, address indexed newVerifier);

Errors

ZkVerifier_ImageNotValid

error ZkVerifier_ImageNotValid();

ZkVerifier_InputNotValid

error ZkVerifier_InputNotValid();

ZkVerifier_VerifierNotSet

error ZkVerifier_VerifierNotSet();

Counter

Git Source

State Variables

number

uint256 public number;

Functions

setNumber

function setNumber(uint256 newNumber) public;

increment

function increment() public;

Roles

Git Source

Inherits: Ownable, IRoles

State Variables

_roles

mapping(address => mapping(bytes32 => bool)) private _roles;

REBALANCER

bytes32 public constant REBALANCER = keccak256("REBALANCER");

PAUSE_MANAGER

bytes32 public constant PAUSE_MANAGER = keccak256("PAUSE_MANAGER");

REBALANCER_EOA

bytes32 public constant REBALANCER_EOA = keccak256("REBALANCER_EOA");

GUARDIAN_PAUSE

bytes32 public constant GUARDIAN_PAUSE = keccak256("GUARDIAN_PAUSE");

CHAINS_MANAGER

bytes32 public constant CHAINS_MANAGER = keccak256("CHAINS_MANAGER");

PROOF_FORWARDER

bytes32 public constant PROOF_FORWARDER = keccak256("PROOF_FORWARDER");

PROOF_BATCH_FORWARDER

bytes32 public constant PROOF_BATCH_FORWARDER = keccak256("PROOF_BATCH_FORWARDER");

SEQUENCER

bytes32 public constant SEQUENCER = keccak256("SEQUENCER");

GUARDIAN_BRIDGE

bytes32 public constant GUARDIAN_BRIDGE = keccak256("GUARDIAN_BRIDGE");

GUARDIAN_ORACLE

bytes32 public constant GUARDIAN_ORACLE = keccak256("GUARDIAN_ORACLE");

GUARDIAN_RESERVE

bytes32 public constant GUARDIAN_RESERVE = keccak256("GUARDIAN_RESERVE");

GUARDIAN_BORROW_CAP

bytes32 public constant GUARDIAN_BORROW_CAP = keccak256("GUARDIAN_BORROW_CAP");

GUARDIAN_SUPPLY_CAP

bytes32 public constant GUARDIAN_SUPPLY_CAP = keccak256("GUARDIAN_SUPPLY_CAP");

Functions

constructor

constructor(address _owner) Ownable(_owner);

isAllowedFor

function isAllowedFor(address _contract, bytes32 _role) external view override returns (bool);

allowFor

Abiltity to allow a contract for a role or not

function allowFor(address _contract, bytes32 _role, bool _allowed) external onlyOwner;

Parameters

NameTypeDescription
_contractaddressthe contract's address.
_rolebytes32the bytes32 role.
_allowedboolthe new status.

Events

Allowed

emitted when role is set

event Allowed(address indexed _contract, bytes32 indexed _role, bool _allowed);