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
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
Name | Type | Description |
---|---|---|
user | address | The user address |
state | bool | The 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
Name | Type | Description |
---|---|---|
newCloseFactorMantissa | uint256 | New 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
Name | Type | Description |
---|---|---|
mToken | address | The market to set the factor on |
newCollateralFactorMantissa | uint256 | The new collateral factor, scaled by 1e18 |
setLiquidationIncentive
Sets liquidationIncentive
Admin function to set liquidationIncentive
function setLiquidationIncentive(address market, uint256 newLiquidationIncentiveMantissa) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
market | address | |
newLiquidationIncentiveMantissa | uint256 | New 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
Name | Type | Description |
---|---|---|
mToken | address | The address of the market (token) to list |
setOutflowVolumeTimeWindow
Sets outflow volume time window
function setOutflowVolumeTimeWindow(uint256 newTimeWindow) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
newTimeWindow | uint256 | The new reset time window |
setOutflowTimeLimitInUSD
Sets outflow volume limit
when 0, it means there's no limit
function setOutflowTimeLimitInUSD(uint256 amount) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The new limit |
resetOutflowVolume
Resets outflow volume
function resetOutflowVolume() external onlyOwner;
checkOutflowVolumeLimit
Verifies outflow volule limit
function checkOutflowVolumeLimit(uint256 amount) external;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The 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
Name | Type | Description |
---|---|---|
mTokens | address[] | The addresses of the markets (tokens) to change the borrow caps for |
newBorrowCaps | uint256[] | 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
Name | Type | Description |
---|---|---|
mTokens | address[] | The addresses of the markets (tokens) to change the supply caps for |
newSupplyCaps | uint256[] | 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
Name | Type | Description |
---|---|---|
mToken | address | The market token address |
_type | ImTokenOperationTypes.OperationType | The pause operation type |
state | bool | The pause operation status |
setRewardDistributor
Admin function to change the Reward Distributor
function setRewardDistributor(address newRewardDistributor) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
newRewardDistributor | address | The 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
Name | Type | Description |
---|---|---|
mToken | address | The mToken to check |
_type | ImTokenOperationTypes.OperationType | the operation type |
getAssetsIn
Returns the assets an account has entered
function getAssetsIn(address _user) external view override returns (address[] memory mTokens);
Parameters
Name | Type | Description |
---|---|---|
_user | address | The address of the account to pull assets for |
Returns
Name | Type | Description |
---|---|---|
mTokens | address[] | 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
Name | Type | Description |
---|---|---|
account | address | The address of the account to check |
mToken | address | The mToken to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
mToken | address | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | account 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
Name | Type | Description |
---|---|---|
account | address | The account to determine liquidity for |
mTokenModify | address | The market to hypothetically redeem/borrow in |
redeemTokens | uint256 | The number of tokens to hypothetically redeem |
borrowAmount | uint256 | The amount of underlying to hypothetically borrow |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | hypothetical 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
Name | Type | Description |
---|---|---|
mTokenBorrowed | address | The address of the borrowed mToken |
mTokenCollateral | address | The address of the collateral mToken |
actualRepayAmount | uint256 | The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | number 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
Name | Type | Description |
---|---|---|
_mTokens | address[] | 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
Name | Type | Description |
---|---|---|
_account | address | The 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
Name | Type | Description |
---|---|---|
_mToken | address | The 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
Name | Type | Description |
---|---|---|
holder | address | The 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
Name | Type | Description |
---|---|---|
holder | address | The address to claim MALDA for |
mTokens | address[] | 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
Name | Type | Description |
---|---|---|
holders | address[] | The addresses to claim MALDA for |
mTokens | address[] | The list of markets to claim MALDA in |
borrowers | bool | Whether or not to claim MALDA earned by borrowing |
suppliers | bool | Whether 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
Name | Type | Description |
---|---|---|
user | address | The user to check |
beforeBorrowOnExtension
Checks whitelist status on borrowOnExtension
function beforeBorrowOnExtension(address user) external view onlyAllowedUser(user);
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
beforeRebalancing
Checks if the account should be allowed to rebalance tokens
function beforeRebalancing(address mToken) external view override;
Parameters
Name | Type | Description |
---|---|---|
mToken | address | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the transfer against |
src | address | The account which sources the tokens |
dst | address | The account which receives the tokens |
transferTokens | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the mint against |
minter | address | The 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
Name | Type | Description |
---|---|---|
mToken | address | Asset 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the redeem against |
redeemer | address | The account which would redeem the tokens |
redeemTokens | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the borrow against |
borrower | address | The account which would borrow the asset |
borrowAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the repay against |
borrower | address | The 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
Name | Type | Description |
---|---|---|
mTokenBorrowed | address | Asset which was borrowed by the borrower |
mTokenCollateral | address | Asset which was used as collateral and will be seized |
borrower | address | The address of the borrower |
repayAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
mTokenCollateral | address | Asset which was used as collateral and will be seized |
mTokenBorrowed | address | Asset which was borrowed by the borrower |
liquidator | address | The address repaying the borrow and seizing the collateral |
borrower | address | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market whose supply index to update |
_updateMaldaBorrowIndex
Notify reward distributor for borrow index update
function _updateMaldaBorrowIndex(address mToken) private;
Parameters
Name | Type | Description |
---|---|---|
mToken | address | The market whose borrow index to update |
_distributeSupplierMalda
Notify reward distributor for supplier update
function _distributeSupplierMalda(address mToken, address supplier) private;
Parameters
Name | Type | Description |
---|---|---|
mToken | address | The market in which the supplier is interacting |
supplier | address | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market in which the borrower is interacting |
borrower | address | The 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
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
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
Name | Type | Description |
---|---|---|
blocksPerYear_ | uint256 | The estimated number of blocks per year |
baseRatePerYear | uint256 | The base APR, scaled by 1e18 |
multiplierPerYear | uint256 | The rate increase in interest wrt utilization, scaled by 1e18 |
jumpMultiplierPerYear | uint256 | The multiplier per block after utilization point |
kink_ | uint256 | The utilization point where the jump multiplier applies |
owner_ | address | The owner of the contract |
name_ | string | A 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
Name | Type | Description |
---|---|---|
baseRatePerYear | uint256 | The approximate target base APR, as a mantissa (scaled by 1e18) |
multiplierPerYear | uint256 | The rate of increase in interest rate wrt utilization (scaled by 1e18) |
jumpMultiplierPerYear | uint256 | The multiplierPerBlock after hitting a specified utilization point |
kink_ | uint256 | The 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
Name | Type | Description |
---|---|---|
blocksPerYear_ | uint256 | The 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
Name | Type | Description |
---|---|---|
cash | uint256 | The total cash in the market |
borrows | uint256 | The total borrows in the market |
reserves | uint256 | The total reserves in the market |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
cash | uint256 | The total cash in the market |
borrows | uint256 | The total borrows in the market |
reserves | uint256 | The total reserves in the market |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
cash | uint256 | The total cash in the market |
borrows | uint256 | The total borrows in the market |
reserves | uint256 | The total reserves in the market |
reserveFactorMantissa | uint256 | The current reserve factor for the market |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
baseRatePerYear | uint256 | The base APR, scaled by 1e18 |
multiplierPerYear | uint256 | The rate increase wrt utilization, scaled by 1e18 |
jumpMultiplierPerYear | uint256 | The multiplier per block after utilization point |
kink_ | uint256 | The utilization point where the jump multiplier applies |
Errors
JumpRateModelV4_MultiplierNotValid
error JumpRateModelV4_MultiplierNotValid();
Contents
- external
- IBridge
- IDefaultAdapter
- IInterestRateModel
- IOperatorData
- IOperatorDefender
- IOperator
- IOracleOperator
- IOwnable
- IPauser
- IRebalanceMarket
- IRebalancer
- IRewardDistributorData
- IRewardDistributor
- IRoles
- ImErc20
- ImErc20Host
- ImTokenOperationTypes
- ImTokenDelegator
- ImTokenMinimal
- ImToken
- ImTokenGateway
Contents
Contents
IAcrossReceiverV3
Functions
handleV3AcrossMessage
function handleV3AcrossMessage(address tokenSent, uint256 amount, address relayer, bytes memory message) external;
IAcrossSpokePoolV3
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
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
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
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
Name | Type | Description |
---|---|---|
_destinations | uint32[] | The possible destination chains of the intent |
_receiver | address | The destinantion address of the intent |
_inputAsset | address | The asset address on origin |
_outputAsset | address | The asset address on destination |
_amount | uint256 | The amount of the asset |
_maxFee | uint24 | The maximum fee that can be taken by solvers |
_ttl | uint48 | The time to live of the intent |
_data | bytes | The data of the intent |
Returns
Name | Type | Description |
---|---|---|
_intentId | bytes32 | The ID of the intent |
_intent | Intent | The intent object |
Structs
Intent
struct Intent {
uint256 val;
}
Contents
Contents
- MessagingParams
- MessagingReceipt
- MessagingFee
- Origin
- ILayerZeroEndpointV2
- SendParam
- OFTLimit
- OFTReceipt
- OFTFeeDetail
- ILayerZeroOFT
- ILayerZeroReceiverV2
- MessageLibType
- IMessageLib
- SetConfigParam
- IMessageLibManager
- IMessagingChannel
- IMessagingComposer
- IMessagingContext
MessagingParams
struct MessagingParams {
uint32 dstEid;
bytes32 receiver;
bytes message;
bytes options;
bool payInLzToken;
}
MessagingReceipt
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
MessagingFee
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
Origin
struct Origin {
uint32 srcEid;
bytes32 sender;
uint64 nonce;
}
ILayerZeroEndpointV2
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
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
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
Struct representing OFT receipt information.
struct OFTReceipt {
uint256 amountSentLD;
uint256 amountReceivedLD;
}
OFTFeeDetail
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
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
Name | Type | Description |
---|---|---|
interfaceId | bytes4 | The interface ID. |
version | uint64 | The version. |
token
Retrieves the address of the token associated with the OFT.
function token() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | token 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
Name | Type | Description |
---|---|---|
<none> | bool | requiresApproval Needs approval of the underlying token implementation. |
sharedDecimals
Retrieves the shared decimals of the OFT.
function sharedDecimals() external view returns (uint8);
Returns
Name | Type | Description |
---|---|---|
<none> | uint8 | sharedDecimals 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
Name | Type | Description |
---|---|---|
_sendParam | SendParam | The parameters for the send operation. |
Returns
Name | Type | Description |
---|---|---|
<none> | OFTLimit | limit The OFT limit information. |
oftFeeDetails | OFTFeeDetail[] | The details of OFT fees. |
<none> | OFTReceipt | receipt 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
Name | Type | Description |
---|---|---|
_sendParam | SendParam | The parameters for the send() operation. |
_payInLzToken | bool | Flag indicating whether the caller is paying in the LZ token. |
Returns
Name | Type | Description |
---|---|---|
<none> | MessagingFee | fee 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
Name | Type | Description |
---|---|---|
_sendParam | SendParam | The parameters for the send operation. |
_fee | MessagingFee | The fee information supplied by the caller. - nativeFee: The native fee. - lzTokenFee: The lzToken fee. |
_refundAddress | address | The address to receive any excess funds from fees etc. on the src. |
Returns
Name | Type | Description |
---|---|---|
<none> | MessagingReceipt | receipt The LayerZero messaging receipt from the send() operation. |
<none> | OFTReceipt | oftReceipt 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
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
enum MessageLibType {
Send,
Receive,
SendAndReceive
}
IMessageLib
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
struct SetConfigParam {
uint32 eid;
uint32 configType;
bytes config;
}
IMessageLibManager
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
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
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
Functions
isSendingMessage
function isSendingMessage() external view returns (bool);
getSendContext
function getSendContext() external view returns (uint32 dstEid, address sender);
ILayerZeroEndpoint
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
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
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
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
Name | Type | Description |
---|---|---|
signature | bytes | The signature to check |
human | address | the address for which the signature has been crafted |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True if the signature was made by signer, false otherwise |
getSigner
Returns the signer's address
function getSigner() external view returns (address);
IBridge
Functions
getFee
computes fee for bridge operation
function getFee(uint32 _dstChainId, bytes memory _message, bytes memory _bridgeData) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
_dstChainId | uint32 | destination chain id |
_message | bytes | operation message data |
_bridgeData | bytes | specific 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
Name | Type | Description |
---|---|---|
_extractedAmount | uint256 | extracted amount for rebalancing |
_market | address | destination address |
_dstChainId | uint32 | destination chain id |
_token | address | the token to rebalance |
_message | bytes | operation message data |
_bridgeData | bytes | specific bridge datas |
IDefaultAdapter
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
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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The base rate per block |
jumpMultiplierPerBlock
The multiplierPerBlock after hitting a specified utilization point
function jumpMultiplierPerBlock() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The jump multiplier per block |
kink
The utilization point at which the jump multiplier is applied
function kink() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The utilization point (kink) |
name
A name for user-friendliness, e.g. WBTC
function name() external view returns (string memory);
Returns
Name | Type | Description |
---|---|---|
<none> | string | The 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
Name | Type | Description |
---|---|---|
cash | uint256 | The total cash in the market |
borrows | uint256 | The total borrows in the market |
reserves | uint256 | The total reserves in the market |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
cash | uint256 | The total cash in the market |
borrows | uint256 | The total borrows in the market |
reserves | uint256 | The total reserves in the market |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
cash | uint256 | The total cash in the market |
borrows | uint256 | The total borrows in the market |
reserves | uint256 | The total reserves in the market |
reserveFactorMantissa | uint256 | The current reserve factor for the market |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
baseRatePerBlock | uint256 | The base rate per block |
multiplierPerBlock | uint256 | The multiplier per block for the interest rate slope |
jumpMultiplierPerBlock | uint256 | The multiplier after hitting the kink |
kink | uint256 | The utilization point where the jump multiplier is applied |
IOperatorData
Structs
Market
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
mapping(address => bool) accountMembership;
bool isMalded;
}
IOperatorDefender
Functions
beforeRebalancing
Checks if the account should be allowed to rebalance tokens
function beforeRebalancing(address mToken) external;
Parameters
Name | Type | Description |
---|---|---|
mToken | address | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the transfer against |
src | address | The account which sources the tokens |
dst | address | The account which receives the tokens |
transferTokens | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the mint against |
minter | address | The account which would get the minted tokens |
afterMTokenMint
Validates mint and reverts on rejection. May emit logs.
function afterMTokenMint(address mToken) external view;
Parameters
Name | Type | Description |
---|---|---|
mToken | address | Asset 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the redeem against |
redeemer | address | The account which would redeem the tokens |
redeemTokens | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the borrow against |
borrower | address | The account which would borrow the asset |
borrowAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The market to verify the repay against |
borrower | address | The 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
Name | Type | Description |
---|---|---|
mTokenBorrowed | address | Asset which was borrowed by the borrower |
mTokenCollateral | address | Asset which was used as collateral and will be seized |
borrower | address | The address of the borrower |
repayAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
mTokenCollateral | address | Asset which was used as collateral and will be seized |
mTokenBorrowed | address | Asset which was borrowed by the borrower |
liquidator | address | The address repaying the borrow and seizing the collateral |
borrower | address | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | New amount |
beforeWithdrawOnExtension
Checks whitelist status on withdrawOnExtension
function beforeWithdrawOnExtension(address user) external view;
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
beforeBorrowOnExtension
Checks whitelist status on borrowOnExtension
function beforeBorrowOnExtension(address user) external view;
Parameters
Name | Type | Description |
---|---|---|
user | address | The user to check |
IOperator
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
Name | Type | Description |
---|---|---|
mToken | address | The mToken to check |
_type | ImTokenOperationTypes.OperationType | the 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
Name | Type | Description |
---|---|---|
_user | address | The address of the account to pull assets for |
Returns
Name | Type | Description |
---|---|---|
mTokens | address[] | 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
Name | Type | Description |
---|---|---|
account | address | The address of the account to check |
mToken | address | The mToken to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True 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
Name | Type | Description |
---|---|---|
<none> | uint256 | account 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
Name | Type | Description |
---|---|---|
account | address | The account to determine liquidity for |
mTokenModify | address | The market to hypothetically redeem/borrow in |
redeemTokens | uint256 | The number of tokens to hypothetically redeem |
borrowAmount | uint256 | The amount of underlying to hypothetically borrow |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | hypothetical 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
Name | Type | Description |
---|---|---|
mTokenBorrowed | address | The address of the borrowed mToken |
mTokenCollateral | address | The address of the collateral mToken |
actualRepayAmount | uint256 | The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | number 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
Name | Type | Description |
---|---|---|
mToken | address | The market to check if deprecated |
setPaused
Set pause for a specific operation
function setPaused(address mToken, ImTokenOperationTypes.OperationType _type, bool state) external;
Parameters
Name | Type | Description |
---|---|---|
mToken | address | The market token address |
_type | ImTokenOperationTypes.OperationType | The pause operation type |
state | bool | The pause operation status |
enterMarkets
Add assets to be included in account liquidity calculation
function enterMarkets(address[] calldata _mTokens) external;
Parameters
Name | Type | Description |
---|---|---|
_mTokens | address[] | 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
Name | Type | Description |
---|---|---|
_account | address | The 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
Name | Type | Description |
---|---|---|
_mToken | address | The address of the asset to be removed |
claimMalda
Claim all the MALDA accrued by holder in all markets
function claimMalda(address holder) external;
Parameters
Name | Type | Description |
---|---|---|
holder | address | The 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
Name | Type | Description |
---|---|---|
holder | address | The address to claim MALDA for |
mTokens | address[] | 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
Name | Type | Description |
---|---|---|
holders | address[] | The addresses to claim MALDA for |
mTokens | address[] | The list of markets to claim MALDA in |
borrowers | bool | Whether or not to claim MALDA earned by borrowing |
suppliers | bool | Whether or not to claim MALDA earned by supplying |
IOracleOperator
Prices are returned in USD
Functions
getPrice
Get the price of a mToken asset
function getPrice(address mToken) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
mToken | address | The mToken to get the price of |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The mToken to get the underlying price of |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The underlying asset price mantissa (scaled by 1e18). Zero means the price is unavailable. |
IOwnable
Functions
transferOwnership
function transferOwnership(address newOwner) external;
IPauser
Inherits: ImTokenOperationTypes
Functions
emergencyPauseMarket
pauses all operations for a market
function emergencyPauseMarket(address _market) external;
Parameters
Name | Type | Description |
---|---|---|
_market | address | the mToken address |
emergencyPauseMarketFor
pauses a specific operation for a market
function emergencyPauseMarketFor(address _market, OperationType _pauseType) external;
Parameters
Name | Type | Description |
---|---|---|
_market | address | the mToken address |
_pauseType | OperationType | the 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
Functions
extractForRebalancing
function extractForRebalancing(uint256 amount) external;
IRebalancer
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
Name | Type | Description |
---|---|---|
bridge | address | the whitelisted bridge address |
_market | address | the market to rebalance from address |
_amount | uint256 | the amount to rebalance |
msg | Msg | the 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
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
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
Name | Type | Description |
---|---|---|
_token | address | the 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
Name | Type | Description |
---|---|---|
holders | address[] | 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
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
Name | Type | Description |
---|---|---|
_contract | address | the contract address |
_role | bytes32 | the bytes32 role |
Errors
Roles_InputNotValid
error Roles_InputNotValid();
ImErc20
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
Name | Type | Description |
---|---|---|
mintAmount | uint256 | The amount of the underlying asset to supply |
receiver | address | The mTokens receiver |
minAmountOut | uint256 | The 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
Name | Type | Description |
---|---|---|
redeemTokens | uint256 | The 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
Name | Type | Description |
---|---|---|
redeemAmount | uint256 | The amount of underlying to redeem |
borrow
Sender borrows assets from the protocol to their own address
function borrow(uint256 borrowAmount) external;
Parameters
Name | Type | Description |
---|---|---|
borrowAmount | uint256 | The amount of the underlying asset to borrow |
repay
Sender repays their own borrow
function repay(uint256 repayAmount) external returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
repayAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
borrower | address | the account with the debt being payed off |
repayAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
borrower | address | The borrower of this mToken to be liquidated |
repayAmount | uint256 | The amount of the underlying borrowed asset to repay |
mTokenCollateral | address | The market in which to seize collateral from the borrower |
addReserves
The sender adds to reserves.
function addReserves(uint256 addAmount) external;
Parameters
Name | Type | Description |
---|---|---|
addAmount | uint256 | The amount fo underlying token to add as reserves |
ImErc20Host
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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of underlying to be accounted for |
minAmount | uint256 | The min amount of underlying to be accounted for |
receiver | address | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of underlying to be accounted for |
borrower | address | The address that borrow is executed for |
receiver | address |
extractForRebalancing
Extract amount to be used for rebalancing operation
function extractForRebalancing(uint256 amount) external;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to rebalance |
updateAllowedCallerStatus
Set caller status for msg.sender
function updateAllowedCallerStatus(address caller, bool status) external;
Parameters
Name | Type | Description |
---|---|---|
caller | address | The caller address |
status | bool | The 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
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data for minting (array of encoded journals) |
seal | bytes | The Zk proof seal |
userToLiquidate | address[] | Array of positions to liquidate |
liquidateAmount | uint256[] | Array of amounts to liquidate |
collateral | address[] | Array of collaterals to seize |
receiver | address | The 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
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data for minting (array of encoded journals) |
seal | bytes | The Zk proof seal |
mintAmount | uint256[] | Array of amounts to mint |
minAmountsOut | uint256[] | Array of min amounts accepted |
receiver | address | The tokens receiver |
repayExternal
Repays tokens after external verification
function repayExternal(
bytes calldata journalData,
bytes calldata seal,
uint256[] calldata repayAmount,
address receiver
) external;
Parameters
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data for repayment (array of encoded journals) |
seal | bytes | The Zk proof seal |
repayAmount | uint256[] | Array of amounts to repay |
receiver | address | The position to repay for |
withdrawOnExtension
Initiates a withdraw operation
function withdrawOnExtension(uint256 amount, uint32 dstChainId) external payable;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to withdraw |
dstChainId | uint32 | The destination chain to recieve funds |
borrowOnExtension
Initiates a withdraw operation
function borrowOnExtension(uint256 amount, uint32 dstChainId) external payable;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to withdraw |
dstChainId | uint32 | The 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
Enums
OperationType
enum OperationType {
AmountIn,
AmountInHere,
AmountOut,
AmountOutHere,
Seize,
Transfer,
Mint,
Borrow,
Repay,
Redeem,
Liquidate,
Rebalancing
}
ImTokenDelegator
Functions
delegate
Non-standard token able to delegate
function delegate(address delegatee) external;
ImTokenMinimal
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
Name | Type | Description |
---|---|---|
account | address | The 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
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
Name | Type | Description |
---|---|---|
dst | address | The address of the recipient |
amount | uint256 | The number of tokens to transfer |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
src | address | The address from which tokens are transferred |
dst | address | The address to which tokens are transferred |
amount | uint256 | The number of tokens to transfer |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
spender | address | The address authorized to spend tokens |
amount | uint256 | The number of tokens to approve |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
owner | address | The address of the token holder |
spender | address | The address authorized to spend the tokens |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
owner | address | The address to query the balance for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The balance of tokens owned by owner |
balanceOfUnderlying
Returns the underlying asset balance of the owner
function balanceOfUnderlying(address owner) external returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
owner | address | The address to query the balance of underlying assets for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
account | address | The address to query the account snapshot for |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
<none> | uint256 | The current borrow rate per block, scaled by 1e18 |
supplyRatePerBlock
Returns the current supply rate per block
function supplyRatePerBlock() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The current supply rate per block, scaled by 1e18 |
totalBorrowsCurrent
Returns the total amount of borrows, accounting for interest
function totalBorrowsCurrent() external returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total amount of borrows |
borrowBalanceCurrent
Returns the current borrow balance for account
, accounting for interest
function borrowBalanceCurrent(address account) external returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
account | address | The address to query the borrow balance for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The current borrow balance |
borrowBalanceStored
Returns the stored borrow balance for account
, without accruing interest
function borrowBalanceStored(address account) external view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
account | address | The address to query the stored borrow balance for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The stored borrow balance |
exchangeRateCurrent
Returns the current exchange rate, with interest accrued
function exchangeRateCurrent() external returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The current exchange rate |
exchangeRateStored
Returns the stored exchange rate, without accruing interest
function exchangeRateStored() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The stored exchange rate |
getCash
Returns the total amount of available cash in the contract
function getCash() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
liquidator | address | The account receiving seized collateral |
borrower | address | The account having collateral seized |
seizeTokens | uint256 | The number of mTokens to seize |
reduceReserves
Accrues interest and reduces reserves by transferring to admin
function reduceReserves(uint256 reduceAmount) external;
Parameters
Name | Type | Description |
---|---|---|
reduceAmount | uint256 | Amount of reduction to reserves |
ImTokenGateway
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
Name | Type | Description |
---|---|---|
<none> | address | The address of the underlying token |
isPaused
returns pause state for operation
function isPaused(ImTokenOperationTypes.OperationType _type) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_type | ImTokenOperationTypes.OperationType | the 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to rebalance |
setPaused
Set pause for a specific operation
function setPaused(ImTokenOperationTypes.OperationType _type, bool state) external;
Parameters
Name | Type | Description |
---|---|---|
_type | ImTokenOperationTypes.OperationType | The pause operation type |
state | bool | The pause operation status |
updateAllowedCallerStatus
Set caller status for msg.sender
function updateAllowedCallerStatus(address caller, bool status) external;
Parameters
Name | Type | Description |
---|---|---|
caller | address | The caller address |
status | bool | The status to set for caller |
supplyOnHost
Supply underlying to the contract
function supplyOnHost(uint256 amount, address receiver, bytes4 lineaSelector) external payable;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The supplied amount |
receiver | address | The receiver address |
lineaSelector | bytes4 | The 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
Name | Type | Description |
---|---|---|
journalData | bytes | The supplied journal |
seal | bytes | The seal address |
amounts | uint256[] | The amounts to withdraw for each journal |
receiver | address | The 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
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
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
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
Functions
approve
function approve(address spender, uint256 amount) external returns (bool);
SafeApprove
Functions
safeApprove
function safeApprove(address token, address to, uint256 value) internal;
Errors
SafeApprove_NoContract
error SafeApprove_NoContract();
SafeApprove_Failed
error SafeApprove_Failed();
mTokenProofDecoderLib
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
- extension
- host
- BatchSubmitter
- mErc20
- mErc20Immutable
- mErc20Upgradable
- mToken
- mTokenConfiguration
- mTokenStorage
Contents
mTokenGateway
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
Name | Type | Description |
---|---|---|
_type | OperationType | the 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
Name | Type | Description |
---|---|---|
user | address | The user address |
state | bool | The 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
Name | Type | Description |
---|---|---|
_type | OperationType | The pause operation type |
state | bool | The pause operation status |
extractForRebalancing
Extract amount to be used for rebalancing operation
function extractForRebalancing(uint256 amount) external notPaused(OperationType.Rebalancing);
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to rebalance |
setUnderlying
function setUnderlying(address _addr) external onlyOwner;
setGasFee
Sets the gas fee
function setGasFee(uint256 amount) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | the new gas fee |
withdrawGasFees
Withdraw gas received so far
function withdrawGasFees(address payable receiver) external;
Parameters
Name | Type | Description |
---|---|---|
receiver | address payable | the receiver address |
updateZkVerifier
Updates IZkVerifier address
function updateZkVerifier(address _zkVerifier) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
_zkVerifier | address | the verifier address |
updateAllowedCallerStatus
Set caller status for msg.sender
function updateAllowedCallerStatus(address caller, bool status) external override;
Parameters
Name | Type | Description |
---|---|---|
caller | address | The caller address |
status | bool | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | The supplied amount |
receiver | address | The receiver address |
lineaSelector | bytes4 | The 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
Name | Type | Description |
---|---|---|
journalData | bytes | The supplied journal |
seal | bytes | The seal address |
amounts | uint256[] | The amounts to withdraw for each journal |
receiver | address | The 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
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
Name | Type | Description |
---|---|---|
underlying_ | address | The address of the underlying asset |
operator_ | address | The address of the Operator |
interestRateModel_ | address | The address of the interest rate model |
initialExchangeRateMantissa_ | uint256 | The initial exchange rate, scaled by 1e18 |
name_ | string | ERC-20 name of this token |
symbol_ | string | ERC-20 symbol of this token |
decimals_ | uint8 | ERC-20 decimal precision of this token |
admin_ | address payable | Address of the administrator of this token |
zkVerifier_ | address | The 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
Name | Type | Description |
---|---|---|
_chainId | uint32 | the chain id |
_status | bool | the new status |
extractForRebalancing
Extract amount to be used for rebalancing operation
function extractForRebalancing(uint256 amount) external;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to rebalance |
setMigrator
Sets the migrator address
function setMigrator(address _migrator) external onlyAdmin;
Parameters
Name | Type | Description |
---|---|---|
_migrator | address | The new migrator address |
setGasFee
Sets the gas fee
function setGasFee(uint32 dstChainId, uint256 amount) external onlyAdmin;
Parameters
Name | Type | Description |
---|---|---|
dstChainId | uint32 | the destination chain id |
amount | uint256 | the gas fee amount |
withdrawGasFees
Withdraw gas received so far
function withdrawGasFees(address payable receiver) external;
Parameters
Name | Type | Description |
---|---|---|
receiver | address payable | the receiver address |
updateZkVerifier
Updates IZkVerifier address
function updateZkVerifier(address _zkVerifier) external onlyAdmin;
Parameters
Name | Type | Description |
---|---|---|
_zkVerifier | address | the verifier address |
updateAllowedCallerStatus
Set caller status for msg.sender
function updateAllowedCallerStatus(address caller, bool status) external override;
Parameters
Name | Type | Description |
---|---|---|
caller | address | The caller address |
status | bool | The 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
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data for minting (array of encoded journals) |
seal | bytes | The Zk proof seal |
userToLiquidate | address[] | Array of positions to liquidate |
liquidateAmount | uint256[] | Array of amounts to liquidate |
collateral | address[] | Array of collaterals to seize |
receiver | address | The 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
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data for minting (array of encoded journals) |
seal | bytes | The Zk proof seal |
mintAmount | uint256[] | Array of amounts to mint |
minAmountsOut | uint256[] | Array of min amounts accepted |
receiver | address | The tokens receiver |
repayExternal
Repays tokens after external verification
function repayExternal(
bytes calldata journalData,
bytes calldata seal,
uint256[] calldata repayAmount,
address receiver
) external override;
Parameters
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data for repayment (array of encoded journals) |
seal | bytes | The Zk proof seal |
repayAmount | uint256[] | Array of amounts to repay |
receiver | address | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to withdraw |
dstChainId | uint32 | The destination chain to recieve funds |
borrowOnExtension
Initiates a withdraw operation
function borrowOnExtension(uint256 amount, uint32 dstChainId) external payable override;
Parameters
Name | Type | Description |
---|---|---|
amount | uint256 | The amount to withdraw |
dstChainId | uint32 | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of underlying to be accounted for |
minAmount | uint256 | The min amount of underlying to be accounted for |
receiver | address | The 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
Name | Type | Description |
---|---|---|
amount | uint256 | The amount of underlying to be accounted for |
borrower | address | The address that borrow is executed for |
receiver | address |
_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
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
Name | Type | Description |
---|---|---|
_zkVerifier | address | the 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
Name | Type | Description |
---|---|---|
journalData | bytes | The journal data to verify |
seal | bytes | The 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
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
Name | Type | Description |
---|---|---|
underlying_ | address | The address of the underlying asset |
operator_ | address | The address of the Operator |
interestRateModel_ | address | The address of the interest rate model |
initialExchangeRateMantissa_ | uint256 | The initial exchange rate, scaled by 1e18 |
name_ | string | ERC-20 name of this token |
symbol_ | string | ERC-20 symbol of this token |
decimals_ | uint8 | ERC-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
Name | Type | Description |
---|---|---|
delegatee | address | The 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
Name | Type | Description |
---|---|---|
token | IERC20 | The 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
Name | Type | Description |
---|---|---|
mintAmount | uint256 | The amount of the underlying asset to supply |
receiver | address | The mTokens receiver |
minAmountOut | uint256 | The 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
Name | Type | Description |
---|---|---|
redeemTokens | uint256 | The 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
Name | Type | Description |
---|---|---|
redeemAmount | uint256 | The amount of underlying to redeem |
borrow
Sender borrows assets from the protocol to their own address
function borrow(uint256 borrowAmount) external checkSameChainAllowed;
Parameters
Name | Type | Description |
---|---|---|
borrowAmount | uint256 | The amount of the underlying asset to borrow |
repay
Sender repays their own borrow
function repay(uint256 repayAmount) external checkSameChainAllowed returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
repayAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
borrower | address | the account with the debt being payed off |
repayAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
borrower | address | The borrower of this mToken to be liquidated |
repayAmount | uint256 | The amount of the underlying borrowed asset to repay |
mTokenCollateral | address | The market in which to seize collateral from the borrower |
addReserves
The sender adds to reserves.
function addReserves(uint256 addAmount) external;
Parameters
Name | Type | Description |
---|---|---|
addAmount | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
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
Name | Type | Description |
---|---|---|
underlying_ | address | The address of the underlying asset |
operator_ | address | The address of the Operator |
interestRateModel_ | address | The address of the interest rate model |
initialExchangeRateMantissa_ | uint256 | The initial exchange rate, scaled by 1e18 |
name_ | string | ERC-20 name of this token |
symbol_ | string | ERC-20 symbol of this token |
decimals_ | uint8 | ERC-20 decimal precision of this token |
admin_ | address payable | Address of the administrator of this token |
mErc20Upgradable
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
Name | Type | Description |
---|---|---|
underlying_ | address | The address of the underlying asset |
operator_ | address | The address of the Operator |
interestRateModel_ | address | The address of the interest rate model |
initialExchangeRateMantissa_ | uint256 | The initial exchange rate, scaled by 1e18 |
name_ | string | ERC-20 name of this token |
symbol_ | string | ERC-20 symbol of this token |
decimals_ | uint8 | ERC-20 decimal precision of this token |
admin_ | address payable |
mToken
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
Name | Type | Description |
---|---|---|
operator_ | address | The address of the Operator |
interestRateModel_ | address | The address of the interest rate model |
initialExchangeRateMantissa_ | uint256 | The initial exchange rate, scaled by 1e18 |
name_ | string | EIP-20 name of this token |
symbol_ | string | EIP-20 symbol of this token |
decimals_ | uint8 | EIP-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
Name | Type | Description |
---|---|---|
owner | address | The address of the token holder |
spender | address | The address authorized to spend the tokens |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
owner | address |
balanceOfUnderlying
Returns the underlying asset balance of the owner
function balanceOfUnderlying(address owner) external override returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
owner | address | The address to query the balance of underlying assets for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
account | address | The address to query the account snapshot for |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
<none> | uint256 | The current borrow rate per block, scaled by 1e18 |
supplyRatePerBlock
Returns the current supply rate per block
function supplyRatePerBlock() external view override returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
account | address | The address to query the stored borrow balance for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The stored borrow balance |
getCash
Returns the total amount of available cash in the contract
function getCash() external view override returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total amount of cash |
exchangeRateStored
Returns the stored exchange rate, without accruing interest
function exchangeRateStored() external view override returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The stored exchange rate |
transfer
Transfers amount
tokens to the dst
address
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool);
Parameters
Name | Type | Description |
---|---|---|
dst | address | The address of the recipient |
amount | uint256 | The number of tokens to transfer |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
src | address | The address from which tokens are transferred |
dst | address | The address to which tokens are transferred |
amount | uint256 | The number of tokens to transfer |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
spender | address | The address authorized to spend tokens |
amount | uint256 | The number of tokens to approve |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether the approval was successful or not |
totalBorrowsCurrent
Returns the total amount of borrows, accounting for interest
function totalBorrowsCurrent() external override nonReentrant returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
account | address | The address to query the borrow balance for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The current borrow balance |
exchangeRateCurrent
Returns the current exchange rate, with interest accrued
function exchangeRateCurrent() public override nonReentrant returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
liquidator | address | The account receiving seized collateral |
borrower | address | The account having collateral seized |
seizeTokens | uint256 | The number of mTokens to seize |
reduceReserves
Accrues interest and reduces reserves by transferring to admin
function reduceReserves(uint256 reduceAmount) external override nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
reduceAmount | uint256 | Amount of reduction to reserves |
_borrowBalanceStored
Return the borrow balance of account based on stored data
function _borrowBalanceStored(address account) internal view returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
account | address | The address whose balance should be calculated |
Returns
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
user | address | The user address |
receiver | address | |
mintAmount | uint256 | The amount of the underlying asset to supply |
minAmountOut | uint256 | The minimum amount to be received |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
user | address | The user address |
redeemTokens | uint256 | The number of mTokens to redeem into underlying |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
user | address | The user address |
redeemAmount | uint256 | The amount of underlying to receive from redeeming mTokens |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
user | address | The user address |
borrowAmount | uint256 | The amount of the underlying asset to borrow |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
user | address | The user address |
receiver | address | The underlying receiver address |
borrowAmount | uint256 | The amount of the underlying asset to borrow |
_repay
Sender repays their own borrow
function _repay(uint256 repayAmount, bool doTransfer) internal nonReentrant returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
repayAmount | uint256 | The amount to repay, or type(uint256).max for the full outstanding amount |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
borrower | address | the account with the debt being payed off |
repayAmount | uint256 | The amount to repay, or type(uint256).max for the full outstanding amount |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
liquidator | address | The liquidator address |
borrower | address | The borrower of this mToken to be liquidated |
repayAmount | uint256 | The amount of the underlying borrowed asset to repay |
mTokenCollateral | address | The market in which to seize collateral from the borrower |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
seizerToken | address | The contract seizing the collateral (i.e. borrowed mToken) |
liquidator | address | The account receiving seized collateral |
borrower | address | The account having collateral seized |
seizeTokens | uint256 | The number of mTokens to seize |
_addReserves
Accrues interest and reduces reserves by transferring from msg.sender
function _addReserves(uint256 addAmount) internal nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
addAmount | uint256 | Amount 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
Name | Type | Description |
---|---|---|
liquidator | address | The address repaying the borrow and seizing collateral |
borrower | address | The borrower of this mToken to be liquidated |
repayAmount | uint256 | The amount of the underlying borrowed asset to repay |
mTokenCollateral | address | The market in which to seize collateral from the borrower |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
payer | address | the account paying off the borrow |
borrower | address | the account with the debt being payed off |
repayAmount | uint256 | the amount of underlying tokens being returned, or type(uint256).max for the full outstanding amount |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
borrower | address payable | |
receiver | address payable | |
borrowAmount | uint256 | The amount of the underlying asset to borrow |
doTransfer | bool |
__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
Name | Type | Description |
---|---|---|
minter | address | The address of the account which is supplying the assets |
receiver | address | The address of the account which is receiving the assets |
mintAmount | uint256 | The amount of the underlying asset to supply |
minAmountOut | uint256 | The min amount to be received |
doTransfer | bool | If 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
Name | Type | Description |
---|---|---|
spender | address | The address of the account performing the transfer |
src | address | The address of the source account |
dst | address | The address of the destination account |
tokens | uint256 | The number of tokens to transfer |
mTokenConfiguration
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
Name | Type | Description |
---|---|---|
newInterestRateModel | address | the 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
Name | Type | Description |
---|---|---|
newPendingAdmin | address payable | New 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
Name | Type | Description |
---|---|---|
newInterestRateModel | address | the new interest rate model to use |
_setOperator
function _setOperator(address _operator) internal;
mTokenStorage
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
Name | Type | Description |
---|---|---|
<none> | uint256 | calculated 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
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
Functions
getAssetsIn
function getAssetsIn(address account) external view returns (IMendiMarket[] memory);
Migrator
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
Name | Type | Description |
---|---|---|
params | MigrationParams | Migration parameters containing protocol addresses |
getAllPositions
Get all migratable
positions from Mendi to Malda
function getAllPositions(MigrationParams calldata params) external returns (Position[] memory positions);
Parameters
Name | Type | Description |
---|---|---|
params | MigrationParams | Migration parameters containing protocol addresses |
migrateAllPositions
Migrates all positions from Mendi to Malda
function migrateAllPositions(MigrationParams calldata params) external;
Parameters
Name | Type | Description |
---|---|---|
params | MigrationParams | Migration 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
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
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
Name | Type | Description |
---|---|---|
mToken | address | The mToken to get the price of |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
mToken | address | The mToken to get the underlying price of |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
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
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
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
Name | Type | Description |
---|---|---|
_contract | address | the pausable contract |
_contractType | PausableType | the pausable contract type |
removePausableMarket
removes pauable contract
function removePausableMarket(address _contract) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
_contract | address | the pausable contract |
emergencyPauseMarket
pauses all operations for a market
function emergencyPauseMarket(address _market) external;
Parameters
Name | Type | Description |
---|---|---|
_market | address | the mToken address |
emergencyPauseMarketFor
pauses a specific operation for a market
function emergencyPauseMarketFor(address _market, ImTokenOperationTypes.OperationType _pauseType) external;
Parameters
Name | Type | Description |
---|---|---|
_market | address | the mToken address |
_pauseType | ImTokenOperationTypes.OperationType | the 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
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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
_extractedAmount | uint256 | extracted amount for rebalancing |
_market | address | destination address |
_dstChainId | uint32 | destination chain id |
_token | address | the token to rebalance |
_message | bytes | operation message data |
<none> | bytes |
handleV3AcrossMessage
handles AcrossV3 SpokePool message
function handleV3AcrossMessage(address tokenSent, uint256 amount, address, bytes memory message)
external
onlySpokePool
nonReentrant;
Parameters
Name | Type | Description |
---|---|---|
tokenSent | address | the token address received |
amount | uint256 | the token amount |
<none> | address | |
message | bytes | the 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
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
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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
_extractedAmount | uint256 | extracted amount for rebalancing |
_market | address | destination address |
_dstChainId | uint32 | destination chain id |
_token | address | the token to rebalance |
_message | bytes | operation 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
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
Name | Type | Description |
---|---|---|
<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
Name | Type | Description |
---|---|---|
_extractedAmount | uint256 | extracted amount for rebalancing |
_market | address | destination address |
_dstChainId | uint32 | destination chain id |
_token | address | the token to rebalance |
_message | bytes | operation 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
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
Name | Type | Description |
---|---|---|
_dstChainId | uint32 | destination chain id |
_message | bytes | operation message data |
_composeMsg | bytes |
sendMsg
rebalance through bridge
function sendMsg(
uint256 _extractedAmount,
address _market,
uint32 _dstChainId,
address _token,
bytes memory _message,
bytes memory _composeMsg
) external payable onlyRebalancer;
Parameters
Name | Type | Description |
---|---|---|
_extractedAmount | uint256 | extracted amount for rebalancing |
_market | address | destination address |
_dstChainId | uint32 | destination chain id |
_token | address | the token to rebalance |
_message | bytes | operation message data |
_composeMsg | bytes |
_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
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
Name | Type | Description |
---|---|---|
_bridge | address | |
_market | address | the market to rebalance from address |
_amount | uint256 | the amount to rebalance |
_msg | Msg |
Structs
TransferInfo
struct TransferInfo {
uint256 size;
uint256 timestamp;
}
Contents
ReferralSigning
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
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
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
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
Functions
getBorrowerPosition
function getBorrowerPosition(address borrower, address market)
external
view
returns (bool shouldLiquidate, uint256 repayAmount);
IWrappedNative
Functions
deposit
function deposit() external payable;
transfer
function transfer(address to, uint256 value) external returns (bool);
withdraw
function withdraw(uint256) external;
WrapAndSupply
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
Name | Type | Description |
---|---|---|
mToken | address | The market address |
receiver | address | The mToken receiver |
minAmount | uint256 |
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
Name | Type | Description |
---|---|---|
mTokenGateway | address | The market address |
receiver | address | The receiver |
selector | bytes4 | The 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
Functions
verifyInput
function verifyInput(bytes calldata journalEntry, bytes calldata seal) external view;
ZkVerifier
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
Name | Type | Description |
---|---|---|
_risc0Verifier | address | the new IRiscZeroVerifier address |
setImageId
Sets the image id
Admin check is needed on the external method
function setImageId(bytes32 _imageId) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
_imageId | bytes32 | the new image id |
verifyInput
Verifies an input
function verifyInput(bytes calldata journalEntry, bytes calldata seal) external view;
Parameters
Name | Type | Description |
---|---|---|
journalEntry | bytes | the risc0 journal entry |
seal | bytes | the 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
State Variables
number
uint256 public number;
Functions
setNumber
function setNumber(uint256 newNumber) public;
increment
function increment() public;
Roles
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
Name | Type | Description |
---|---|---|
_contract | address | the contract's address. |
_role | bytes32 | the bytes32 role. |
_allowed | bool | the new status. |
Events
Allowed
emitted when role is set
event Allowed(address indexed _contract, bytes32 indexed _role, bool _allowed);