Malda Lending Protocol – Technical Overview
Malda is a modern lending protocol enhanced with cross-chain capabilities using zk-coprocessor proofs (Risc0) and extension gateways for remote execution. It retains core economic primitives of a secure lending protocol, while introducing mTokenHost / mTokenGateway pairs for cross-chain liquidity and borrowing.
🔧 Core Components
Operator
Purpose
The Operator contract is the central authority that governs markets, collateral factors, account liquidity, liquidation thresholds, and policy enforcement (who can mint, redeem, borrow, repay etc).
The Operator serves as the protocol’s risk management layer, enforcing collateral requirements and determining liquidation conditions. It evaluates each user’s position to decide the necessary collateral and the extent of possible liquidation. Every time a user interacts with an mToken, the Operator assesses and approves or rejects the transaction.
It interacts with mTokens, IPriceOracle, and IInterestRateModel to ensure the stability and security of the platform.
Responsibilities
- Market listing and pausing
- Setting risk parameters (collateral factor, liquidation incentive, caps)
- Computing account liquidity and shortfall
- Authorizing mints, redeems, borrows, repayments, liquidations
- Disable/Enable whitelist
- Define outflow volume time and value limits (outflow volume defines the maximum amount of tokens that can go through sequencer between a specified time window)
- Compute each user's account liquidity or shortfall (determine how much a user can borrow based on their supplied assets and collateral factors)
The following Operator methods act as notification/trigger for various mToken lending operations
function beforeMTokenTransfer(address mToken, address src, address dst, uint256 transferTokens) external;
function beforeMTokenMint(address mToken, address minter) external;
function afterMTokenMint(address mToken) external view;
function beforeMTokenRedeem(address mToken, address redeemer, uint256 redeemTokens) external;
function beforeMTokenBorrow(address mToken, address borrower, uint256 borrowAmount) external;
function beforeMTokenRepay(address mToken, address borrower) external;
function beforeMTokenLiquidate(
address mTokenBorrowed,
address mTokenCollateral,
address borrower,
uint256 repayAmount
) external view;
function beforeMTokenSeize(address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower) external;
As mentioned, Operator acts as a guardian for the mToken contract. Below is a list of methods created for this purpose:
function rolesOperator() external view returns (IRoles);
function oracleOperator() external view returns (address);
function closeFactorMantissa() external view returns (uint256);
function liquidationIncentiveMantissa() external view returns (uint256);
function getAssetsIn(address _user) external view returns (address[] memory mTokens);
function getAllMarkets() external view returns (address[] memory mTokens);
function borrowCaps(address _mToken) external view returns (uint256);
function supplyCaps(address _mToken) external view returns (uint256);
function rewardDistributor() external view returns (address);
mErc20Host
This contract represents a lending market on the host chain (Linea). The mErc20Host contract extends mErc20Upgradeable and provides cross-chain money market functionalities using zk-proof verification. It interacts with mTokenProofDecoderLib for proof decoding and adheres to ImErc20Host interface.
Purpose
- Accept deposits
- Issue mTokens (Malda interest-bearing tokens)
- Track underlying balance and user shares
- Uses
IRolescontract for role-based permissioning. - Uses
ZkVerifierto verify proof data before allowing withdrawals. This is usingRisc0libraries under the hood (Steel) - Admin and specific roles (example:
GUARDIAN_PAUSE,REBALANCER,PROOF_FORWARDER) can perform privileged actions. - Support mint/redeem/borrow/repay on the local chain
function mint(uint256 mintAmount) external; function redeem(uint256 redeemTokens) external; function redeemUnderlying(uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repay(uint256 repayAmount) external; function repayBehalf(address borrower, uint256 repayAmount) external; function liquidate(address borrower, uint256 repayAmount, address mTokenCollateral) external; function addReserves(uint256 addAmount) external; - Validate and execute zk-coprocessor proofs for cross-chain operations
-
Accumulated{} struct tracks cumulative deposits and withdrawals per user and chain. Both the mTokenGateway (described in next section) and mErc20Host markets accumulate amountsIn and amountsOut per user. Whenever there’s a supply operation performed, the amountsIn is increased. That means that when the proof is submitted on the destination chain the proof was generated for it checks the difference between received amountIn and that chain’s registered amountIn. This difference represents the maximum amount the user can use for operations tied to an amountIn flow, like mint, repay, liquidate.
-
Cross-chain ZK operations: Accepts proof inputs from the zk-coprocessor that attest a valid state transition from another chain. Once verified, calls local internal methods to:
function liquidateExternal function mintExternal function repayExternal -
Remote borrowing/withdrawal: Via
performExtensionCall; this contract emits an event or performs outbound call intended to be picked up by the sequencer to the destination chain.
-
mToken amount is computed according to the following formula (mTokenBalance* exchangeRate / 10^18 / 10^(underlying token decimals)) * underlying_price. The underlying_price is retrieved fromMixedPriceOracleV3 oracle implementation
mTokenGateway (Extension Market)
This contract mirrors the mTokenHost, but lives on an extension chain.
The mTokenGateway contract serves as a gateway for handling token operations similar to the mErc20Host contract. It’s the extensions (not Linea) chains’ equivalent of a market.
It has support for role-based access control, proof verification, and cross-chain interactions. It manages deposits, withdrawals, and caller permissions while ensuring security through zero-knowledge (ZK) proof validation.
You can think of the mTokenGateway as a small version of a market or a market’s gateway as the only important operations this is handling are: supplying tokens or withdrawing tokens.
Unique Behavior
- Doesn’t store full balance logic — that lives in the Host
- All actual capital sits on the host chain
- Exposes simplified interface for supply type actions which are only valid once settled on the host chain
- Uses
IRolescontract for role-based permissioning. - Uses
ZkVerifierto verify proof data before allowing withdrawals. This is usingrisc0libraries under the hood (Steel)
function supplyOnHost(uint256 amount, bytes4 lineaSelector) external override notPaused(OperationType.AmountIn)
function outHere(bytes calldata journalData, bytes calldata seal, uint256 amount, address receiver)
When funds are supplied accAmountIn is increased. This is part of the proof generated with getProofData
/**
* @inheritdoc ImTokenGateway
*/
function getProofData(address user) external view returns (bytes memory) {
return mTokenProofDecoderLib.encodeJournal(
user, address(this), accAmountIn[user], accAmountOut[user], uint32(block.chainid), LINEA_CHAIN_ID
);
}
The mTokenProofDecoderLib is performing an abi.encodePacked operation on the data provided and uses BytesLib for the decode operation.
return abi.encodePacked(sender, market, accAmountIn, accAmountOut, chainId, dstChainId);
🔁 Cross-Chain Flow
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
Extension to Host (Deposit / Proof Flow)
-
User deposits tokens into
mTokenGateway(extension). -
Extension records this and updates its internal state hash.
-
ZK coprocessor (Risc0) proves this transition off-chain.
-
Proof is sent to
mErc20Host, which verifies it. -
Host mints (or any other supply type action allowed by the host contract) tokens for the user and updates supply.
Host to Extension (Withdraw / Borrow Flow)
-
User initiates
borroworwithdrawonmErc20HostusingperformExtensionCallmethod. -
Contract emits a cross-chain event / message.
-
The sequencer picks up the message.
-
mTokenGatewayfinalizes the borrow or redeem action.
ZK Coprocessor Proof Validation
The ZkVerifier contract is an abstract contract designed to facilitate the verification of zero-knowledge proofs using the Risc0 framework. It manages a verifier contract instance, an image ID, and provides methods for verifying inputs based on cryptographic proofs. Uses Steel to verify a proof
The following code illustrates how a verification performed:
function __verify(bytes calldata journalEntry, bytes calldata seal) private view {
verifier.verify(seal, imageId, sha256(journalEntry));
}
Proofs are generated using getProofData() calls available on mTokenGateway and mErc20Host contracts. A proof consists of the following fields:
- the user for which the proof is generated for;
user - the market address the proof is intended to be used for;
market - the accumulated amount in for user on the current chain the proof is generated on;
accAmountIn[user] - the accumulated amount out for user on the current chain the proof is generated on;
accAmountOut[user] - the current chain id in uint32 format;
uint32(block.chainid) - the destination chain id in uint32 format;
LINEA_CHAIN_ID
The above fields are part of the mTokenGateway proof. The difference between getProofData() from mTokenGateway and getProofData() from mErc20Host contract is that the host call also needs the destination chain id to generate the proof for. This is skipped on mTokenGateway as the destination is always Linea, defined by LINEA_CHAIN_ID
uint32 private constant LINEA_CHAIN_ID = 59144;
Security is enforced by requiring proof verification before state updates.
Users have the ability to self-sequence the transactions for themselves, in case of Sequencer failure or if they wish to do it for themselves.
BatchSubmitter
The BatchSubmitter contract facilitates batch processing of multiple operations in a single transaction. It uses zk-proof verification by implementing the Steel library and interacts with mErc20Host and mTokenGateway contracts to execute minting, repaying and withdrawing.
bytes4 internal constant MINT_SELECTOR = ImErc20Host.mintExternal.selector;
bytes4 internal constant REPAY_SELECTOR = ImErc20Host.repayExternal.selector;
bytes4 internal constant OUT_HERE_SELECTOR = ImTokenGateway.outHere.selector;
Pauser
The Pauser contract provides emergency pause functionality for market operations within the lending protocol. It allows the owner and authorized roles to pause individual or all market operations in case of an emergency. The contract maintains a registry of pausable markets and their types, enabling controlled break of operations.
The Pauser acts as a guardian for pausable contracts. It can be integrated with solutions like Hypernative to emergency pause 1 operation of a market, the entire market or even all pausable contracts in 1 tx.
// pause a market entirely
function emergencyPauseMarket(address _market) external;
// pause a specific operation for a market
function emergencyPauseMarketFor(address _market, OperationType _pauseType) external;
// pause everything configured in the Pauser contract
function emergencyPauseAll() external;
Interest Model
Borrow APR
The interest rate model for borrowed assets can be calculated using the following formula:
= Base + Multiplier * min(UtilizationRate, Kink) + max(JumpMultiplier * UtilizationRate - Kink, 0)
Supply APR
The interest rate model for supplying assets can be calculated using the following formula: = Distribute (Interest Paid by Borrowers Per Block - Reserve) to all suppliers, and convert it into APY
`= Distribute [(1 + Borrow APY) ^ (1 / BlocksPerYear) - 1] * Total Borrow * (1 - Reserve Factor)` to all suppliers, and convert it into APY
`= {[(1 + Borrow APY) ^ (1 / BlocksPerYear) - 1] * Total Borrow * (1 - Reserve Factor) / Total Supply}`, and convert it into APY
`= {1 + [(1 + Borrow APY) ^ (1/BlocksPerYear) - 1] * Total Borrow * (1 - Reserve Factor) / Total Supply} ^ BlocksPerYear - 1`
Using the same interest model as Mendi: https://docs.mendi.finance/protocol/interest-rate-model
Rebalancer
The Rebalancer contract is responsible for managing liquidity rebalancing across different markets and chains. It ensures that funds can be transferred securely using whitelisted bridge contracts while maintaining a log of all rebalancing messages.
It extracts funds from mTokenGateway or mErc20Host contracts and sends to another layer, to the same market, using an implemented IBridge .
The rebalancing module continuously monitors borrow activity on Malda and other money markets, chains’ inflows and outflows, and additional metrics to forecast future borrow demand per chain to rebalance token balances across chains.
The expected borrow demand for a token on a chain is forecasted based on a linear regression of the borrow demand over the last 7 days. If forecasts are shown to be inaccurate, other formulas will be used to minimize the observed delta.
Additional signals include deviations in general borrow demand on other money markets or outliers of chain inflows/outflows.
// retrieve amounts (make sure to check min and max for that bridge) IRebalanceMarket(_market).extractForRebalancing(_amount); ... IBridge(_bridge).sendMsg{value: msg.value}(_msg.dstChainId, _msg.token, _msg.message, _msg.bridgeData);
Key aspects:
- Manages whitelisted bridge contracts
- Sends messages for rebalancing across chains
- Ensures only authorized addresses can perform rebalancing operations
- Logs rebalancing messages to maintain a history
- Ensures only authorized roles can modify bridge whitelisting and initiate rebalancing.
- Prevents unauthorized token transfers by checking
_underlyingmatches_msg.token. - Uses
SafeApproveto mitigate token approval risks.
Across bridge (IBridge)
The AccrossBridge contract facilitates cross-chain liquidity transfers using the Across protocol. It extends BaseBridge and implements IBridge . It integrates with the Across Spoke Pool for cross-chain transfers.
Everclear bridge (IBridge)
The EverclearBridge contract enables cross-chain liquidity transfers using the Everclear protocol. It extends BaseBridge and implements IBridge . It integrates with IEverclearSpoke to send cross-chain liquidity.
Implements getFee to estimate transfer costs.
Deployer
The Deployer contract is responsible for deploying other smart contracts using CREATE3. It allows an admin to create contracts deterministically, retrieve precomputed addresses, and manage contract deployment permissions.
Key aspects:
- Uses
CREATE3to deploy contracts deterministically - Allows the admin to precompute contract addresses
- Provides mechanisms for transferring ETH stored in the contract
- Enables admin role management
The Deployer contract will be deployed using CREATE2 on multiple chains. The following is similar to the CREATE3Factory contract, except that it’s protected by admin role.
CREATE3 is implemented by the following library:
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.8.28;
import {Bytes32AddressLib} from "./Bytes32AddressLib.sol";
/// @notice Deploy to deterministic addresses without an initcode factor.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/CREATE3.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/create3/blob/master/contracts/Create3.sol)
library CREATE3 {
using Bytes32AddressLib for bytes32;
//--------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//--------------------------------------------------------------------------------//
// 0x36 | 0x36 | CALLDATASIZE | size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 0 size //
// 0x37 | 0x37 | CALLDATACOPY | //
// 0x36 | 0x36 | CALLDATASIZE | size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 size //
// 0x34 | 0x34 | CALLVALUE | value 0 size //
// 0xf0 | 0xf0 | CREATE | newContract //
//--------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//--------------------------------------------------------------------------------//
// 0x67 | 0x67XXXXXXXXXXXXXXXX | PUSH8 bytecode | bytecode //
// 0x3d | 0x3d | RETURNDATASIZE | 0 bytecode //
// 0x52 | 0x52 | MSTORE | //
// 0x60 | 0x6008 | PUSH1 08 | 8 //
// 0x60 | 0x6018 | PUSH1 18 | 24 8 //
// 0xf3 | 0xf3 | RETURN | //
//--------------------------------------------------------------------------------//
bytes internal constant PROXY_BYTECODE = hex"67363d3d37363d34f03d5260086018f3";
bytes32 internal constant PROXY_BYTECODE_HASH = keccak256(PROXY_BYTECODE);
function deploy(bytes32 salt, bytes memory creationCode, uint256 value) internal returns (address deployed) {
bytes memory proxyChildBytecode = PROXY_BYTECODE;
address proxy;
assembly {
// Deploy a new contract with our pre-made bytecode via CREATE2.
// We start 32 bytes into the code to avoid copying the byte length.
proxy := create2(0, add(proxyChildBytecode, 32), mload(proxyChildBytecode), salt)
}
require(proxy != address(0), "DEPLOYMENT_FAILED");
deployed = getDeployed(salt);
(bool success,) = proxy.call{value: value}(creationCode);
require(success && deployed.code.length != 0, "INITIALIZATION_FAILED");
}
function getDeployed(bytes32 salt) internal view returns (address) {
address proxy = keccak256(abi.encodePacked(bytes1(0xFF), address(this), salt, PROXY_BYTECODE_HASH))
// Prefix:
// Creator:
// Salt:
// Bytecode hash:
.fromLast20Bytes();
return keccak256(abi.encodePacked(hex"d694", proxy, hex"01")) // Nonce of the proxy contract (1)
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01)
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)
.fromLast20Bytes();
}
}
🚀 Dev Onboarding & Recipes
Malda has multiple new use cases and advantages compared to traditional architecture:
-
Ability to use 1 (!) money market as a DeFi bank to manage all investments through the major rollups of the Ethereum ecosystem
-
Seamless arbitrage across chains with borrowed funds between DEXs
-
Easy and convenient user-experience without needing to disrupt user flow to bridge between chains.
-
Quick access to investment opportunity with the ability to borrow or withdraw on supported chains instantaneously.
-
Easy migration and access for Ethereum Mainnet liquidity to major rollups
-
Scale and Depth - Currently legacy lending models suffer fragmented liquidity and it is dependent on the underlying chain the quality of the service they can provide. Malda removes this limitation and provides the full depth of liquidity to all served markets, increasing capital efficiency and fostering meaningful economic growth in the Ethereum ecosystem.
Besides the more complex scenarios, Malda allows simple ones as:
Deploy a new market
- Deploy mErc20Host and configure (collateral, reserve factors etc)
- Deploy mTokenGateway and configure (collateral, reserve factors etc)
- Register market in Operator
- Configure interest rate model, oracle, and caps
- Assign roles using IRoles
Minting mTokens
To deposit funds and receive interest-bearing mTokens:
- Approve the mToken contract to spend your underlying token:
IERC20(underlying).approve(mErc20Host, amount);
- Mint mTokens by calling
mErc20Host.mint(amount, receiver, minAmountOut);
Borrowing assets
To borrow assets from the protocol (requires sufficient collateral):
-
Ensure you've minted mTokens of another market as collateral.
-
Call the borrow function:
mErc20Host.borrow(borrowAmount);
Repaying loans
To repay borrowed assets:
- Repay your own loan
IERC20(underlying).approve(mErc20Host, repayAmount);
mErc20Host.repay(repayAmount);
- Repay for another user:
IERC20(underlying).approve(mErc20Host, repayAmount);
mErc20Host.repayBehalf(borrowerAddress, repayAmount);
Redeeming tokens
To withdraw your supplied collateral:
- Redeem by token amount:
mErc20Host.redeem(mTokenAmount);
- Redeem by underlying value:
mErc20Host.redeemUnderlying(underlyingAmount);
Liquidating undercollateralized users
If a user’s borrow exceeds their allowed collateral threshold, you can liquidate their position:
mErc20Host.liquidate(borrower, repayAmount, mTokenCollateral);
Borrow/Withdraw on extension chains
To borrow or redeem on an extension chain, the action initiated on host is:
function performExtensionCall(uint256 actionType, uint256 amount, uint32 dstChainId) external payable
where actionType is: 1-borrow, 2-withdraw
Supply from extension
By supplying on an extension chains you are able to liquidate, mint or repay on host (this is automatically performed by the Sequencer)
function supplyOnHost(uint256 amount, address receiver, bytes4 lineaSelector)
Deployed contracts
Testnet
Deployed on Linea sepolia (host), Sepolia and OP Sepolia
| Name | Address |
|---|---|
| Deployer | 0x7aFcD811e32a9F221B72502bd645d4bAa56a375a |
| Roles | 0x3dc52279175EE96b6A60f6870ec4DfA417c916E3 |
| ZkVerifier | 0xF3CA3C7018eA139E8B3969FF64DafDa8DF946B31 |
| BatchSubmitter | 0xC03155E29276841Bc5D27653c57fb85FA6043C65 |
| GasHelper | 0x3aE44aC156557D30f58E38a6796336E7eD0A3fC1 |
| RewardDistributor | 0x837D67e10C0E91B58568582154222EDF4357D58E |
| MixedPriceOracleV4 | 0xAc028838DaF18FAD0F69a1a1e143Eb8a29b04904 |
| Operator | 0x389cc3D08305C3DaAf19B2Bf2EC7dD7f66D68dA8 |
| Pauser | 0x4EC99a994cC51c03d67531cdD932f231385f9618 |
| mUSDCMock | 0x76daf584Cbf152c85EB2c7Fe7a3d50DaF3f5B6e6 |
| mUSDCMock Interest | 0xfe2E9AB5c7b759CaeA320578844Deae1b696eb32 |
| mwstETHMock | 0xD4286cc562b906589f8232335413f79d9aD42f7E |
| mwstETHMock Interest | 0x10589A75f6D84B932613633831fdE1A4b5945930 |
Mainnet
| Name | Address | Chains |
|---|---|---|
| Deployer | ||
| Roles | ||
| ZkVerifier | ||
| BatchSubmitter | ||
| GasHelper | ||
| RewardDistributor | ||
| MixedPriceOracleV4 | ||
| Operator | ||
| Pauser | ||
| mUSDCMock | ||
| mUSDCMock Interest | ||
| mwstETHMock | ||
| mwstETHMock Interest |
Deployment Architecture
Chains Involved
-
Host Chain: Linea (primary liquidity resides here)
-
Extension Chains: L2s or sidechains like Base, Arbitrum, etc.
Deployment Patterns
- Deterministic deployment via
CREATE3 - ZK proof verification via Risc0 and
Steelensures valid cross-chain operations
Roles and permissions
Pause & Security Management
PAUSE_MANAGER – Manages pausing functionality across contracts via the Pauser contract. Required for calling addPausableMarket
GUARDIAN_PAUSE – Can pause markets by calling setPaused on mTokenGateway and mErc20Host
Market Configuration
GUARDIAN_BORROW_CAP – Can set borrow limits on mTokenGateway and mErc20Host. Required for setMarketBorrowCaps
GUARDIAN_SUPPLY_CAP – Can set supply limits on mTokenGateway and mErc20Host. Required for setMarketSupplyCaps
GUARDIAN_ORACLE – Can configure the oracle by calling .setConfig. Required for `setConfig
GUARDIAN_BRIDGE – Can whitelist bridges on Rebalancer.sol and configure IBridge contracts
Proofs
PROOF_BATCH_FORWARDER – Roles used in BatchSubmitter to enable batch submission of proofs, typically assigned to the relayer
Reserve & Rebalancing
GUARDIAN_RESERVE – Can call reduceReserve on mErc20Host
REBALANCER_EOA – Authorized to call sendMsg on Rebalancer.sol to trigger rebalancing
REBALANCER – Must be assigned to the Rebalancer.sol contract for operational functionality
Cross-Chain Management
CHAINS_MANAGER – Can update the list of allowed destination chains on mErc20Host. Required for calling updateAllowedChain
Contents
EmptyOperator
Title: EmptyOperator
Author: Merge Layers Inc.
Empty operator contract
Functions
isOperator
Checks if the caller is an operator
function isOperator() external pure returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the caller is an operator |
Operator
Inherits: OperatorStorage, ImTokenOperationTypes, OwnableUpgradeable, HypernativeFirewallProtected
Title: Operator core controller
Author: Merge Layers Inc.
Access-controlled operator logic for mTokens
Functions
onlyAllowedUser
Modifier to restrict access to allowed users only
modifier onlyAllowedUser(address user) ;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address to check |
ifNotBlacklisted
Modifier to check if user is not blacklisted
modifier ifNotBlacklisted(address user) ;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address to check |
constructor
Disables initializers for implementation contract
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
initFirewall
Initializes the firewall
function initFirewall(address _firewall) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
_firewall | address | The firewall address |
setBlacklister
Sets the blacklist operator
function setBlacklister(address _blacklister) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
_blacklister | address | The blacklist operator address |
setBorrowSizeMin
Sets min borrow size per market
function setBorrowSizeMin(address[] calldata mTokens, uint256[] calldata amounts) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
mTokens | address[] | The market address |
amounts | uint256[] | The new size |
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 state |
setWhitelistStatus
Sets the whitelist status
function setWhitelistStatus(bool status) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
status | bool | The new status |
setRolesOperator
Sets a new Operator for the market
function setRolesOperator(address _roles) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | The new operator address |
setPriceOracle
Sets a new price oracle
Admin function to set a new price oracle
function setPriceOracle(address newOracle) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
newOracle | address | Address of the new oracle |
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 | 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 volume limit
function checkOutflowVolumeLimit(uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to check |
setMarketBorrowCaps
Set borrow caps for given mToken markets.
Borrowing that brings total borrows to or above borrow cap will revert. A value of 0 corresponds to unlimited borrowing.
function setMarketBorrowCaps(address[] calldata mTokens, uint256[] calldata newBorrowCaps)
external
onlyFirewallApproved;
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. |
setMarketSupplyCaps
Set supply caps for the given mToken markets.
Supplying that brings total supply to or above supply cap will revert. A value of 0 corresponds to unlimited supplying.
function setMarketSupplyCaps(address[] calldata mTokens, uint256[] calldata newSupplyCaps)
external
onlyFirewallApproved;
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. |
setPaused
Set pause for a specific operation
function setPaused(address mToken, ImTokenOperationTypes.OperationType _type, bool state)
external
onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | The market token address |
_type | ImTokenOperationTypes.OperationType | The pause operation type |
state | bool | The pause operation status |
initialize
Initialize the contract
function initialize(address _rolesOperator, address _blacklistOperator, address _admin) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
_rolesOperator | address | The roles operator address |
_blacklistOperator | address | The blacklist operator address |
_admin | address | The admin address |
enterMarkets
Add assets to be included in account liquidity calculation
function enterMarkets(address[] calldata _mTokens)
external
override
onlyAllowedUser(msg.sender)
onlyFirewallApproved;
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, and must not be providing necessary collateral for an outstanding borrow.
function exitMarket(address _mToken) external override onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
_mToken | address | The address of the asset to be removed |
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
ifNotBlacklisted(src)
ifNotBlacklisted(dst)
onlyFirewallApproved;
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 |
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)
ifNotBlacklisted(borrower)
onlyFirewallApproved;
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 |
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | paused True if paused |
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);
Returns
| Name | Type | Description |
|---|---|---|
mTokens | address[] | List of markets |
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | deprecated True if deprecated |
isMarketListed
Returns true/false
function isMarketListed(address mToken) external view override returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | listed True if market is listed |
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 | liquidity Account liquidity in excess of collateral requirements |
<none> | uint256 | shortfall Account shortfall below collateral requirements |
beforeMTokenMint
Checks if the account should be allowed to mint tokens in the given market
function beforeMTokenMint(address mToken, address minter, address receiver)
external
view
override
onlyAllowedUser(minter)
ifNotBlacklisted(minter)
ifNotBlacklisted(receiver)
onlyFirewallApproved
onlyAllowedUser(minter);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | The market to verify the mint against |
minter | address | The account which would supplies the assets |
receiver | 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
view
override
onlyAllowedUser(redeemer)
ifNotBlacklisted(redeemer)
onlyFirewallApproved;
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 |
beforeMTokenRepay
Checks if the account should be allowed to repay a borrow in the given market
function beforeMTokenRepay(address mToken, address borrower)
external
view
onlyAllowedUser(borrower)
onlyFirewallApproved;
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 onlyFirewallApproved;
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)
external
view
override
ifNotBlacklisted(liquidator)
onlyFirewallApproved;
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 |
getUSDValueForAllMarkets
Returns USD value for all markets
function getUSDValueForAllMarkets() external view returns (uint256 sum);
Returns
| Name | Type | Description |
|---|---|---|
sum | uint256 | The total USD value of all markets |
beforeRebalancing
Checks if the account should be allowed to rebalance tokens
function beforeRebalancing(address mToken) external view override onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | The market to verify the transfer against |
firewallRegister
Registers an account with the firewall
function firewallRegister(address _account) public override(HypernativeFirewallProtected);
Parameters
| Name | Type | Description |
|---|---|---|
_account | address | Account to register |
_convertMarketAmountToUSDValue
Converts a market amount to USD value
function _convertMarketAmountToUSDValue(uint256 amount, address mToken) internal view returns (uint256 usdValue);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to convert |
mToken | address | The market to convert |
Returns
| Name | Type | Description |
|---|---|---|
usdValue | uint256 | The USD value of the amount |
_activateMarket
Activates a market for a borrower
function _activateMarket(address _mToken, address borrower) private;
Parameters
| Name | Type | Description |
|---|---|---|
_mToken | address | The market to activate |
borrower | address | The borrower to activate the market for |
_beforeRedeem
Checks if the redeemer is in the market and has sufficient liquidity
function _beforeRedeem(address mToken, address redeemer, uint256 redeemTokens) private view;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | The market to check |
redeemer | address | The redeemer to check |
redeemTokens | uint256 | The number of tokens to redeem |
_getHypotheticalAccountLiquidity
Gets the hypothetical account liquidity
function _getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
) private view returns (uint256, uint256);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | The account to get the liquidity for |
mTokenModify | address | The market to modify |
redeemTokens | uint256 | The number of tokens to redeem |
borrowAmount | uint256 | The amount of underlying to borrow |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | liquidity The liquidity in excess of collateral requirements |
<none> | uint256 | shortfall The shortfall below collateral requirements |
_isDeprecated
Checks if a market is deprecated
function _isDeprecated(address mToken) private view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | The market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | deprecated True if the market is deprecated |
Events
NewBlacklister
Emitted when blacklist operator is updated
event NewBlacklister(address indexed newBlacklister);
Parameters
| Name | Type | Description |
|---|---|---|
newBlacklister | address | The new blacklist operator address |
Errors
Operator_AddressNotValid
Error thrown when address is not valid
error Operator_AddressNotValid();
OperatorStorage
Inherits: IOperator, IOperatorDefender, ExponentialNoError
Title: OperatorStorage
Author: Merge Layers Inc.
Storage contract for Operator
State Variables
CLOSE_FACTOR_MIN_MANTISSA
closeFactorMantissa must be strictly greater than this value
uint256 internal constant CLOSE_FACTOR_MIN_MANTISSA = 0.05e18
CLOSE_FACTOR_MAX_MANTISSA
closeFactorMantissa must not exceed this value
uint256 internal constant CLOSE_FACTOR_MAX_MANTISSA = 0.9e18
COLLATERAL_FACTOR_MAX_MANTISSA
No collateralFactorMantissa may exceed this value
uint256 internal constant COLLATERAL_FACTOR_MAX_MANTISSA = 0.9e18
rolesOperator
Roles
IRoles public rolesOperator
blacklistOperator
Blacklist
IBlacklister public blacklistOperator
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
Mapping of markets to liquidation incentive mantissa
mapping(address market => uint256 incentive) public liquidationIncentiveMantissa
accountAssets
Per-account mapping of "assets you are in", capped by maxAssets
mapping(address account => address[] assets) public accountAssets
markets
Mapping of mTokens to market data
Used e.g. to determine if a market is supported
mapping(address mToken => IOperatorData.Market market) public markets
allMarkets
A list of all markets
address[] public allMarkets
borrowCaps
Mapping of mTokens to borrow caps
mapping(address mToken => uint256 cap) public borrowCaps
supplyCaps
Mapping of mTokens to supply caps
mapping(address mToken => uint256 cap) public supplyCaps
minBorrowSize
Mapping of mTokens to minimum borrow size
mapping(address mToken => uint256 size) public minBorrowSize
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
Mapping of users to whitelist status
mapping(address user => bool whitelisted) public userWhitelisted
whitelistEnabled
Whether whitelist is enabled
bool public whitelistEnabled
_paused
Mapping of mTokens to operation types to pause status
mapping(address mToken => mapping(ImTokenOperationTypes.OperationType actionType => bool paused)) internal _paused
__gap
uint256[50] private __gap
Events
UserWhitelisted
Emitted when user whitelist status is changed
event UserWhitelisted(address indexed user, bool state);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user |
state | bool | Whitelist state |
WhitelistEnabled
Emitted when whitelist is enabled
event WhitelistEnabled();
WhitelistDisabled
Emitted when whitelist is disabled
event WhitelistDisabled();
ActionPaused
Emitted when pause status is changed
event ActionPaused(address indexed mToken, ImTokenOperationTypes.OperationType _type, bool state);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market address |
_type | ImTokenOperationTypes.OperationType | Operation type paused |
state | bool | New pause state |
NewBorrowCap
Emitted when borrow cap for a mToken is changed
event NewBorrowCap(address indexed mToken, uint256 newBorrowCap);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market address |
newBorrowCap | uint256 | New borrow cap |
NewSupplyCap
Emitted when supply cap for a mToken is changed
event NewSupplyCap(address indexed mToken, uint256 newBorrowCap);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market address |
newBorrowCap | uint256 | New supply cap |
MarketListed
Emitted when an admin supports a market
event MarketListed(address mToken);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market listed |
MarketEntered
Emitted when an account enters a market
event MarketEntered(address indexed mToken, address indexed account);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market entered |
account | address | Account entering |
MarketExited
Emitted when an account exits a market
event MarketExited(address indexed mToken, address indexed account);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market exited |
account | address | Account exiting |
NewCloseFactor
Emitted when close factor is changed by admin
event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);
Parameters
| Name | Type | Description |
|---|---|---|
oldCloseFactorMantissa | uint256 | Previous close factor |
newCloseFactorMantissa | uint256 | New close factor |
NewCollateralFactor
Emitted when a collateral factor is changed by admin
event NewCollateralFactor(
address indexed mToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa
);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market address |
oldCollateralFactorMantissa | uint256 | Previous collateral factor |
newCollateralFactorMantissa | uint256 | New collateral factor |
NewLiquidationIncentive
Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(
address market, uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa
);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | Market address |
oldLiquidationIncentiveMantissa | uint256 | Previous incentive |
newLiquidationIncentiveMantissa | uint256 | New incentive |
NewPriceOracle
Emitted when price oracle is changed
event NewPriceOracle(address indexed oldPriceOracle, address indexed newPriceOracle);
Parameters
| Name | Type | Description |
|---|---|---|
oldPriceOracle | address | Previous price oracle |
newPriceOracle | address | New price oracle |
NewRolesOperator
Event emitted when rolesOperator is changed
event NewRolesOperator(address indexed oldRoles, address indexed newRoles);
Parameters
| Name | Type | Description |
|---|---|---|
oldRoles | address | Previous roles operator |
newRoles | address | New roles operator |
OutflowLimitUpdated
Event emitted when outflow limit is updated
event OutflowLimitUpdated(address indexed sender, uint256 oldLimit, uint256 newLimit);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | Caller updating limit |
oldLimit | uint256 | Previous limit |
newLimit | uint256 | New limit |
OutflowTimeWindowUpdated
Event emitted when outflow reset time window is updated
event OutflowTimeWindowUpdated(uint256 oldWindow, uint256 newWindow);
Parameters
| Name | Type | Description |
|---|---|---|
oldWindow | uint256 | Previous window |
newWindow | uint256 | New window |
OutflowVolumeReset
Event emitted when outflow volume has been reset
event OutflowVolumeReset();
MinBorrowSizeSet
Event emitted when min borrow size set for markets
event MinBorrowSizeSet(address[] markets, uint256[] amounts);
Parameters
| Name | Type | Description |
|---|---|---|
markets | address[] | Markets being updated |
amounts | uint256[] | Borrow size amounts |
Errors
Operator_Paused
Error when action is paused
error Operator_Paused();
Operator_Mismatch
Error when data mismatch occurs
error Operator_Mismatch();
Operator_OnlyAdmin
Error when caller is not admin
error Operator_OnlyAdmin();
Operator_EmptyPrice
Error when oracle price is empty
error Operator_EmptyPrice();
Operator_WrongMarket
Error when wrong market is referenced
error Operator_WrongMarket();
Operator_InvalidInput
Error when input is invalid
error Operator_InvalidInput();
Operator_AssetNotFound
Error when asset is not found
error Operator_AssetNotFound();
Operator_RepayingTooMuch
Error when repay amount exceeds allowed
error Operator_RepayingTooMuch();
Operator_OnlyAdminOrRole
Error when caller lacks admin or role permissions
error Operator_OnlyAdminOrRole();
Operator_MarketNotListed
Error when market is not listed
error Operator_MarketNotListed();
Operator_UserBlacklisted
Error when user is blacklisted
error Operator_UserBlacklisted();
Operator_PriceFetchFailed
Error when price fetch fails
error Operator_PriceFetchFailed();
Operator_SenderMustBeToken
Error when sender must be token
error Operator_SenderMustBeToken();
Operator_UserNotWhitelisted
Error when user is not whitelisted
error Operator_UserNotWhitelisted();
Operator_MarketSupplyReached
Error when market supply cap reached
error Operator_MarketSupplyReached();
Operator_RepayAmountNotValid
Error when repay amount invalid
error Operator_RepayAmountNotValid();
Operator_MarketAlreadyListed
Error when market already listed
error Operator_MarketAlreadyListed();
Operator_OutflowVolumeReached
Error when outflow volume reached
error Operator_OutflowVolumeReached();
Operator_InvalidRolesOperator
Error when roles operator invalid
error Operator_InvalidRolesOperator();
Operator_InsufficientLiquidity
Error when insufficient liquidity
error Operator_InsufficientLiquidity();
Operator_MarketBorrowSizeNotMet
Error when borrow size not met
error Operator_MarketBorrowSizeNotMet();
Operator_MarketBorrowCapReached
Error when borrow cap reached
error Operator_MarketBorrowCapReached();
Operator_InvalidCollateralFactor
Error when collateral factor invalid
error Operator_InvalidCollateralFactor();
Operator_InvalidBlacklistOperator
Error when blacklist operator invalid
error Operator_InvalidBlacklistOperator();
Operator_OracleUnderlyingFetchError
Error when oracle underlying fetch fails
error Operator_OracleUnderlyingFetchError();
Operator_Deactivate_MarketBalanceOwed
Error when market has balance owed during deactivation
error Operator_Deactivate_MarketBalanceOwed();
Structs
AccountLiquidityLocalVars
Local vars for avoiding stack-depth limits in calculating account liquidity.
struct AccountLiquidityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowPlusEffects;
/// @notice Number of mTokens the account owns in the market
uint256 mTokenBalance;
/// @notice Amount of underlying that the account has borrowed
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 oraclePriceMantissa;
uint256 collateralFactorMantissa;
uint256 liquidationIncentiveMantissa;
uint256 borrowLimitMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
Contents
Blacklister
Inherits: OwnableUpgradeable, IBlacklister
Title: Blacklister
Author: Merge Layers Inc.
Contract for managing blacklisted addresses
State Variables
isBlacklisted
Mapping of addresses to their blacklist status
mapping(address user => bool isBlacklisted) public isBlacklisted
_blacklistedList
List of blacklisted addresses
address[] private _blacklistedList
rolesOperator
The roles operator contract
IRoles public rolesOperator
Functions
onlyOwnerOrGuardian
Modifier to restrict access to owner or has guardian blacklist role
modifier onlyOwnerOrGuardian() ;
constructor
Disables initializers on implementation contract
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
initialize
Initialize the contract
function initialize(address payable _owner, address _roles) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
_owner | address payable | The owner address |
_roles | address | The roles contract address |
blacklist
Blacklists a user immediately (onlyOwner).
function blacklist(address user) external override onlyOwnerOrGuardian;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to blacklist |
unblacklist
Removes a user from the blacklist (onlyOwner).
function unblacklist(address user) external override onlyOwnerOrGuardian;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to unblacklist |
unblacklist
Removes a user from the blacklist (onlyOwner).
function unblacklist(address user, uint256 index) external override onlyOwnerOrGuardian;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to unblacklist |
index | uint256 | The index of the user in blacklist array |
getBlacklistedAddresses
Returns the list of currently blacklisted addresses.
function getBlacklistedAddresses() external view returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | blacklistedAddresses Array of blacklisted addresses |
_addToBlacklist
Internal function to add an address to blacklist
function _addToBlacklist(address user) internal;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to blacklist |
_removeFromBlacklist
Internal function to remove an address from blacklist list
function _removeFromBlacklist(address user) internal;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to remove |
_removeFromBlacklist
Internal function to remove an address from blacklist list by index
function _removeFromBlacklist(address user, uint256 index) internal;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to remove |
index | uint256 | The index in the blacklist array |
Contents
JumpRateModelV4
Inherits: IInterestRateModel, Ownable
Title: JumpRateModelV4
Author: Merge Layers Inc.
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 baseRatePerBlock_,
uint256 multiplierPerBlock_,
uint256 jumpMultiplierPerBlock_,
uint256 kink_,
address owner_,
string memory name_
) Ownable(owner_);
Parameters
| Name | Type | Description |
|---|---|---|
blocksPerYear_ | uint256 | The estimated number of blocks per year |
baseRatePerBlock_ | uint256 | The base APR, scaled by 1e18 (can be zero) |
multiplierPerBlock_ | uint256 | The rate increase in interest wrt utilization, scaled by 1e18 |
jumpMultiplierPerBlock_ | 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 |
updateJumpRateModelDirect
Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)
function updateJumpRateModelDirect(
uint256 baseRatePerBlock_,
uint256 multiplierPerBlock_,
uint256 jumpMultiplierPerBlock_,
uint256 kink_
) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
baseRatePerBlock_ | uint256 | The approximate target base APR, as a mantissa (scaled by 1e18) |
multiplierPerBlock_ | uint256 | The rate of increase in interest rate wrt utilization (scaled by 1e18) |
jumpMultiplierPerBlock_ | uint256 | The multiplierPerBlock after hitting a specified utilization point |
kink_ | uint256 | The utilization point at which the jump multiplier is applied |
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. |
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 |
isInterestRateModel
Should return true
function isInterestRateModel() external pure override returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isModel True when contract implements interest rate model |
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 |
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] |
_updateBlocksPerYear
Internal function to update blocks per year
function _updateBlocksPerYear(uint256 blocksPerYear_) private;
Parameters
| Name | Type | Description |
|---|---|---|
blocksPerYear_ | uint256 | The new estimated eth blocks per year. |
_updateJumpRateModelWithoutComputation
Internal function to update jump rate model parameters without computation
function _updateJumpRateModelWithoutComputation(
uint256 basePerBlock_,
uint256 multiplierPerBlock_,
uint256 jumpMultiplierPerBlock_,
uint256 kink_
) private;
Parameters
| Name | Type | Description |
|---|---|---|
basePerBlock_ | uint256 | The base rate per block (can be zero) |
multiplierPerBlock_ | uint256 | The multiplier per block |
jumpMultiplierPerBlock_ | uint256 | The jump multiplier per block |
kink_ | uint256 | The kink utilization point |
_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 |
Contents
- external
- IBlacklister
- IBridge
- IDefaultAdapter
- IGasFeesHelper
- IInterestRateModel
- IOperatorData
- IOperatorDefender
- IOperator
- IOracleOperator
- IOwnable
- IPauser
- IRebalanceMarket
- IRebalancer
- IRewardDistributorData
- IRewardDistributor
- IRoles
- ImErc20
- ImErc20Host
- ImTokenOperationTypes
- ImTokenDelegator
- ImTokenMinimal
- ImToken
- ImTokenGateway
Contents
Contents
IAcrossReceiverV3
Functions
handleV3AcrossMessage
handles AcrossV3 SpokePool message
function handleV3AcrossMessage(address tokenSent, uint256 amount, address relayer, bytes memory message) external;
Parameters
| Name | Type | Description |
|---|---|---|
tokenSent | address | the token address received |
amount | uint256 | the token amount |
relayer | address | the relayer submitting the message (unused) |
message | bytes | the custom message sent from source |
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 {
// The address that made the deposit on the origin chain.
address depositor;
// The recipient address on the destination chain.
address recipient;
// This is the exclusive relayer who can fill the deposit before the exclusivity deadline.
address exclusiveRelayer;
// Token that is deposited on origin chain by depositor.
address inputToken;
// Token that is received on destination chain by recipient.
address outputToken;
// The amount of input token deposited by depositor.
uint256 inputAmount;
// The amount of output token to be received by recipient.
uint256 outputAmount;
// Origin chain id.
uint256 originChainId;
// The id uniquely identifying this deposit on the origin chain.
uint32 depositId;
// The timestamp on the destination chain after which this deposit can no longer be filled.
uint32 fillDeadline;
// The timestamp on the destination chain after which any relayer can fill the deposit.
uint32 exclusivityDeadline;
// Data that is forwarded to the recipient.
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,
// Fast fills are normal fills that do not replace a slow fill request.
ReplacedSlowFill,
// Replaced slow fills are fast fills that replace a slow fill request. This type is used by the Dataworker
// to know when to send excess funds from the SpokePool to the HubPool because they can no longer be used
// for a slow fill execution.
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;
}
IFeeAdapter
Functions
newIntent
function newIntent(
uint32[] memory _destinations,
bytes32 _receiver,
address _inputAsset,
bytes32 _outputAsset,
uint256 _amount,
uint24 _maxFee,
uint48 _ttl,
bytes calldata _data,
FeeParams calldata _feeParams
) external payable returns (bytes32 _intentId, Intent memory _intent);
Structs
Intent
struct Intent {
bytes32 initiator;
bytes32 receiver;
bytes32 inputAsset;
bytes32 outputAsset;
uint24 maxFee;
uint32 origin;
uint64 nonce;
uint48 timestamp;
uint48 ttl;
uint256 amount;
uint32[] destinations;
bytes data;
}
FeeParams
struct FeeParams {
uint256 fee;
uint256 deadline;
bytes sig;
}
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; // Destination endpoint ID.
bytes32 to; // Recipient address.
uint256 amountLD; // Amount to send in local decimals.
uint256 minAmountLD; // Minimum amount to send in local decimals.
bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
bytes composeMsg; // The composed message for the send() operation.
bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
OFTLimit
Struct representing OFT limit information.
These amounts can change dynamically and are up the the specific oft implementation.
struct OFTLimit {
uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.
uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}
OFTReceipt
Struct representing OFT receipt information.
struct OFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
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; // Amount of the fee in local decimals.
string description; // Description of the fee.
}
ILayerZeroOFT
Title: IOFT
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( // GUID of the OFT message.
// Destination Endpoint ID.
// Address of the sender on the src chain.
// Amount of tokens sent in local decimals.
// Amount of tokens received in local decimals.
bytes32 indexed guid,
uint32 dstEid,
address indexed fromAddress,
uint256 amountSentLD,
uint256 amountReceivedLD
);
OFTReceived
event OFTReceived( // GUID of the OFT message.
// Source Endpoint ID.
// Address of the recipient on the dst chain.
// Amount of tokens received in local decimals.
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);
IBlacklister
Title: IBlacklister
Author: Merge Layers Inc.
Interface for blacklisting addresses
Functions
blacklist
Blacklists a user immediately (onlyOwner).
function blacklist(address user) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to blacklist |
unblacklist
Removes a user from the blacklist (onlyOwner).
function unblacklist(address user) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to unblacklist |
unblacklist
Removes a user from the blacklist (onlyOwner).
function unblacklist(address user, uint256 index) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to unblacklist |
index | uint256 | The index of the user in blacklist array |
getBlacklistedAddresses
Returns the list of currently blacklisted addresses.
function getBlacklistedAddresses() external view returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | blacklistedAddresses Array of blacklisted addresses |
isBlacklisted
Returns whether a user is currently blacklisted.
function isBlacklisted(address user) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isUserBlacklisted True if the user is blacklisted |
Events
Blacklisted
Emitted when a user is blacklisted
event Blacklisted(address indexed user);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The blacklisted address |
Unblacklisted
Emitted when a user is removed from blacklist
event Unblacklisted(address indexed user);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The unblacklisted address |
Errors
Blacklister_AlreadyBlacklisted
Error thrown when address is already blacklisted
error Blacklister_AlreadyBlacklisted();
Blacklister_NotBlacklisted
Error thrown when address is not blacklisted
error Blacklister_NotBlacklisted();
Blacklister_InvalidRoles
Error thrown when roles contract is invalid
error Blacklister_InvalidRoles();
Blacklister_NotAllowed
Error thrown when caller is not authorized
error Blacklister_NotAllowed();
IBridge
Title: IBridge
Author: Merge Layers Inc.
Interface for rebalancing bridge implementations
Functions
sendMsg
rebalance through bridge
function sendMsg(
uint256 _extractedAmount,
address _market,
uint32 _dstChainId,
address _token,
bytes calldata _message,
bytes calldata _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 |
getFee
computes fee for bridge operation
function getFee(uint32 _dstChainId, bytes calldata _message, bytes calldata _bridgeData)
external
view
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
_dstChainId | uint32 | destination chain id |
_message | bytes | operation message data |
_bridgeData | bytes | specific bridge data |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | fee Computed bridge fee |
IDefaultAdapter
Title: IDefaultAdapter
Author: Merge Layers Inc.
Default price adapter interface used for oracle feeds
Functions
decimals
Returns the decimals for the price feed
function decimals() external view returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | decimalsCount Number of decimals |
latestRoundData
Returns the latest round data from the feed
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
Returns
| Name | Type | Description |
|---|---|---|
roundId | uint80 | Round identifier |
answer | int256 | Feed answer |
startedAt | uint256 | Round start timestamp |
updatedAt | uint256 | Round update timestamp |
answeredInRound | uint80 | The round in which the answer was computed |
latestAnswer
Returns the latest answer
function latestAnswer() external view returns (int256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | int256 | answer Latest feed answer |
latestTimestamp
Returns the latest timestamp
function latestTimestamp() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | timestamp Latest update timestamp |
Structs
PriceConfig
struct PriceConfig {
address defaultFeed; // chainlink & eOracle
string toSymbol;
uint256 underlyingDecimals;
}
IGasFeesHelper
Title: IGasFeesHelper
Author: Merge Layers Inc.
Interface for retrieving per-chain gas fee configuration
Functions
gasFees
Returns the gas fee for a destination chain
function gasFees(uint32 dstChainId) external view returns (uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | Destination chain identifier |
Returns
| Name | Type | Description |
|---|---|---|
fee | uint256 | Gas fee amount |
IInterestRateModel
Title: IInterestRateModel
Author: Merge Layers Inc.
Interface for the interest rate contracts
Functions
isInterestRateModel
Should return true
function isInterestRateModel() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isModel True when contract implements interest rate model |
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 |
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 |
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] |
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 |
BlocksPerYearUpdated
Emitted when blocks per year is updated
event BlocksPerYearUpdated(uint256 blocksPerYear);
Parameters
| Name | Type | Description |
|---|---|---|
blocksPerYear | uint256 | The new blocks per year value |
Errors
JumpRateModelV4_MultiplierNotValid
Error thrown when multiplier is not valid
error JumpRateModelV4_MultiplierNotValid();
JumpRateModelV4_InputNotValid
Error thrown when input is not valid
error JumpRateModelV4_InputNotValid();
JumpRateModelV4_ZeroValueNotAllowed
Error thrown when zero value is not allowed
error JumpRateModelV4_ZeroValueNotAllowed();
IOperatorData
Title: Operator storage structures
Author: Merge Layers Inc.
Data definitions used by Operator contracts
Structs
Market
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint256 collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
}
IOperatorDefender
Title: Operator defender interface
Author: Merge Layers Inc.
Hooks for Operator validation logic
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 |
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 |
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 |
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 |
beforeMTokenRedeem
Checks if the account should be allowed to redeem tokens in the given market
function beforeMTokenRedeem(address mToken, address redeemer, uint256 redeemTokens) external view;
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 |
beforeMTokenRepay
Checks if the account should be allowed to repay a borrow in the given market
function beforeMTokenRepay(address mToken, address borrower) external view;
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) external view;
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 |
beforeMTokenMint
Checks if the account should be allowed to mint tokens in the given market
function beforeMTokenMint(address mToken, address minter, address receiver) external view;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | The market to verify the mint against |
minter | address | The account which would supplies the assets |
receiver | 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 |
IOperator
Title: Operator interface
Author: Merge Layers Inc.
Core Operator contract surface
Functions
userWhitelisted
Returns true/false for user
function userWhitelisted(address _user) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
_user | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | whitelisted True if user is whitelisted |
limitPerTimePeriod
Should return outflow limit
function limitPerTimePeriod() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | limit Outflow limit per period |
cumulativeOutflowVolume
Should return outflow volume
function cumulativeOutflowVolume() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | volume Current outflow volume |
lastOutflowResetTimestamp
Should return last reset time for outflow check
function lastOutflowResetTimestamp() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | lastReset Timestamp of last reset |
outflowResetTimeWindow
Should return the outflow volume time window
function outflowResetTimeWindow() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | window Outflow window |
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | paused True if paused |
rolesOperator
Roles
function rolesOperator() external view returns (IRoles);
Returns
| Name | Type | Description |
|---|---|---|
<none> | IRoles | roles Roles contract |
blacklistOperator
Blacklist
function blacklistOperator() external view returns (IBlacklister);
Returns
| Name | Type | Description |
|---|---|---|
<none> | IBlacklister | blacklister Blacklist operator |
oracleOperator
Oracle which gives the price of any given asset
function oracleOperator() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | oracle Oracle address |
closeFactorMantissa
Multiplier used to calculate the maximum repayAmount when liquidating a borrow
function closeFactorMantissa() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | closeFactor Close factor mantissa |
liquidationIncentiveMantissa
Multiplier representing the discount on collateral that a liquidator receives
function liquidationIncentiveMantissa(address market) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | incentive Discount mantissa |
isMarketListed
Returns true/false
function isMarketListed(address market) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | listed True if market is listed |
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);
Returns
| Name | Type | Description |
|---|---|---|
mTokens | address[] | List of markets |
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);
Parameters
| Name | Type | Description |
|---|---|---|
_mToken | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | cap Borrow cap |
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);
Parameters
| Name | Type | Description |
|---|---|---|
_mToken | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | cap Supply cap |
minBorrowSize
Supply caps enforced by supplyAllowed for each mToken address.
Defaults to zero which corresponds to unlimited borrowing.
function minBorrowSize(address _mToken) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
_mToken | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | minimum Minimum borrow size |
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. |
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 liquidity, uint256 shortfall);
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 |
|---|---|---|
liquidity | uint256 | Account liquidity in excess of collateral requirements |
shortfall | uint256 | Account shortfall below collateral requirements |
getUSDValueForAllMarkets
Returns USD value for all markets
function getUSDValueForAllMarkets() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | usdValue Total USD value |
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | deprecated True 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, and must not 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 |
IOracleOperator
Title: IOracleOperator
Author: Merge Layers Inc.
Oracle operator interface returning USD prices
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 | price The underlying asset price mantissa (scaled by 1e18). Zero means 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 | price The underlying asset price mantissa (scaled by 1e18). Zero means unavailable. |
IOwnable
Title: IOwnable
Author: Merge Layers Inc.
Minimal ownable interface
Functions
transferOwnership
Transfers ownership to a new owner
function transferOwnership(address newOwner) external;
Parameters
| Name | Type | Description |
|---|---|---|
newOwner | address | Address of the new owner |
IPauser
Inherits: ImTokenOperationTypes
Title: IPauser
Author: Merge Layers Inc.
Interface for pausing market operations
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
Emitted when all markets are paused
event PauseAll();
MarketPaused
Emitted when a market is paused
event MarketPaused(address indexed market);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | The paused market |
MarketRemoved
Emitted when a market is removed
event MarketRemoved(address indexed market);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | The market removed |
MarketAdded
Emitted when a market is added
event MarketAdded(address indexed market, PausableType marketType);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | The market added |
marketType | PausableType | The market type |
MarketPausedFor
Emitted when a specific operation is paused for a market
event MarketPausedFor(address indexed market, OperationType pauseType);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | The market paused |
pauseType | OperationType | The operation type paused |
Errors
Pauser_EntryNotFound
Error when entry is not found
error Pauser_EntryNotFound();
Pauser_NotAuthorized
Error when caller lacks authorization
error Pauser_NotAuthorized();
Pauser_AddressNotValid
Error when provided address is invalid
error Pauser_AddressNotValid();
Pauser_AlreadyRegistered
Error when market already registered
error Pauser_AlreadyRegistered();
Pauser_ContractNotEnabled
Error when contract is not enabled
error Pauser_ContractNotEnabled();
Structs
PausableContract
struct PausableContract {
address market;
PausableType contractType;
}
Enums
PausableType
enum PausableType {
NonPausable,
Host,
Extension
}
IRebalanceMarket
Title: IRebalanceMarket
Author: Merge Layers Inc.
Interface for markets supporting rebalancing extractions
Functions
extractForRebalancing
Extract amount to be used for rebalancing
function extractForRebalancing(uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount to extract |
IRebalancer
Title: IRebalancer
Author: Merge Layers Inc.
Interface for rebalancer operations and configuration
Functions
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 |
nonce
Returns current nonce
function nonce() external view returns (uint256 currentNonce);
Returns
| Name | Type | Description |
|---|---|---|
currentNonce | uint256 | Nonce value |
isBridgeWhitelisted
Returns if a bridge implementation is whitelisted
function isBridgeWhitelisted(address bridge) external view returns (bool whitelisted);
Parameters
| Name | Type | Description |
|---|---|---|
bridge | address | Bridge address |
Returns
| Name | Type | Description |
|---|---|---|
whitelisted | bool | True if whitelisted |
isDestinationWhitelisted
Returns if a destination is whitelisted
function isDestinationWhitelisted(uint32 dstId) external view returns (bool whitelisted);
Parameters
| Name | Type | Description |
|---|---|---|
dstId | uint32 | Destination chain ID |
Returns
| Name | Type | Description |
|---|---|---|
whitelisted | bool | True if whitelisted |
isMarketWhitelisted
Returns if a market is whitelisted
function isMarketWhitelisted(address market) external view returns (bool whitelisted);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
whitelisted | bool | True if whitelisted |
Events
BridgeWhitelistedStatusUpdated
Emitted when bridge whitelist status changes
event BridgeWhitelistedStatusUpdated(address indexed bridge, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
bridge | address | Bridge address |
status | bool | Whitelist status |
MsgSent
Emitted when a message is sent through a bridge
event MsgSent(
address indexed bridge, uint32 indexed dstChainId, address indexed token, bytes message, bytes bridgeData
);
Parameters
| Name | Type | Description |
|---|---|---|
bridge | address | Bridge address |
dstChainId | uint32 | Destination chain ID |
token | address | Token address |
message | bytes | Encoded message |
bridgeData | bytes | Bridge-specific data |
EthSaved
Emitted when ETH is saved back to treasury
event EthSaved(uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount saved |
MaxTransferSizeUpdated
Emitted when max transfer size is updated
event MaxTransferSizeUpdated(uint32 indexed dstChainId, address indexed token, uint256 newLimit);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | Destination chain ID |
token | address | Token address |
newLimit | uint256 | New limit |
MinTransferSizeUpdated
Emitted when min transfer size is updated
event MinTransferSizeUpdated(uint32 indexed dstChainId, address indexed token, uint256 newLimit);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | Destination chain ID |
token | address | Token address |
newLimit | uint256 | New limit |
DestinationWhitelistedStatusUpdated
Emitted when destination whitelist status changes
event DestinationWhitelistedStatusUpdated(uint32 indexed dstChainId, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | Destination chain ID |
status | bool | Whitelist status |
AllowedListUpdated
Emitted when allowed list is updated
event AllowedListUpdated(address[] list, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
list | address[] | List of addresses |
status | bool | Whitelist status |
TokensSaved
Emitted when tokens are rescued
event TokensSaved(address indexed token, address indexed market, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address |
market | address | Market address |
amount | uint256 | Amount saved |
AllowedTokensUpdated
Emitted when allowed tokens list is updated for a bridge
event AllowedTokensUpdated(address indexed bridge, bool status, address[] list);
Parameters
| Name | Type | Description |
|---|---|---|
bridge | address | Bridge address |
status | bool | Whitelist status |
list | address[] | Token list |
MarketListUpdated
Emitted when market list is updated
event MarketListUpdated(address[] list, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
list | address[] | Market list |
status | bool | Whitelist status |
Errors
Rebalancer_NotAuthorized
Error thrown when caller not authorized
error Rebalancer_NotAuthorized();
Rebalancer_MarketNotValid
Error thrown when market is not valid
error Rebalancer_MarketNotValid();
Rebalancer_RequestNotValid
Error thrown when request is not valid
error Rebalancer_RequestNotValid();
Rebalancer_AddressNotValid
Error thrown when address is not valid
error Rebalancer_AddressNotValid();
Rebalancer_BridgeNotWhitelisted
Error thrown when bridge is not whitelisted
error Rebalancer_BridgeNotWhitelisted();
Rebalancer_TransferSizeExcedeed
Error thrown when transfer size exceeds maximum
error Rebalancer_TransferSizeExcedeed();
Rebalancer_TransferSizeMinNotMet
Error thrown when transfer size below minimum
error Rebalancer_TransferSizeMinNotMet();
Rebalancer_DestinationNotWhitelisted
Error thrown when destination not whitelisted
error Rebalancer_DestinationNotWhitelisted();
Rebalancer_UnderlyingNotAllowedForBridge
Error thrown when underlying token not allowed for bridge
error Rebalancer_UnderlyingNotAllowedForBridge();
Structs
Msg
struct Msg {
uint32 dstChainId;
address token;
bytes message;
bytes bridgeData;
}
IRewardDistributorData
Title: IRewardDistributorData
Author: Merge Layers Inc.
Storage structs for reward distributor
Structs
RewardMarketState
struct RewardMarketState {
/// @notice The supply speed for each market
uint256 supplySpeed;
/// @notice The supply index for each market
uint224 supplyIndex;
/// @notice The last block timestamp that Reward accrued for supply
uint32 supplyBlock;
/// @notice The borrow speed for each market
uint256 borrowSpeed;
/// @notice The borrow index for each market
uint224 borrowIndex;
/// @notice The last block timestamp that Reward accrued for borrow
uint32 borrowBlock;
}
RewardAccountState
struct RewardAccountState {
/// @notice The supply index for each market as of the last time the account accrued Reward
mapping(address => uint256) supplierIndex;
/// @notice The borrow index for each market as of the last time the account accrued Reward
mapping(address => uint256) borrowerIndex;
/// @notice Accrued Reward but not yet transferred
uint256 rewardAccrued;
}
IRewardDistributor
Title: IRewardDistributor
Author: Merge Layers Inc.
Interface for reward distribution operations
Functions
notifySupplyIndex
Updates supply indices for all reward tokens on a market
function notifySupplyIndex(address mToken) external;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market token |
notifyBorrowIndex
Updates borrow indices for all reward tokens on a market
function notifyBorrowIndex(address mToken) external;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market token |
notifySupplier
Notifies supplier
function notifySupplier(address mToken, address supplier) external;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market token |
supplier | address | Supplier address |
notifyBorrower
Notifies borrower
function notifyBorrower(address mToken, address borrower) external;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market token |
borrower | address | Borrower address |
claim
Claim tokens for holders
function claim(address[] memory holders) external;
Parameters
| Name | Type | Description |
|---|---|---|
holders | address[] | The accounts to claim for |
operator
The operator that rewards are distributed to
function operator() external view returns (address operatorAddress);
Returns
| Name | Type | Description |
|---|---|---|
operatorAddress | address | Operator address |
isRewardToken
Flag to check if reward token added before
function isRewardToken(address _token) external view returns (bool isRewardTokenAdded);
Parameters
| Name | Type | Description |
|---|---|---|
_token | address | The token to check for |
Returns
| Name | Type | Description |
|---|---|---|
isRewardTokenAdded | bool | True if token is a reward token |
getRewardTokens
Added reward tokens
function getRewardTokens() external view returns (address[] memory rewardTokens);
Returns
| Name | Type | Description |
|---|---|---|
rewardTokens | address[] | Array of reward token addresses |
getBlockTimestamp
Get block timestamp
function getBlockTimestamp() external view returns (uint32 timestamp);
Returns
| Name | Type | Description |
|---|---|---|
timestamp | uint32 | Current block timestamp |
Events
RewardAccrued
Emitted when reward is accrued for a user
event RewardAccrued(address indexed rewardToken, address indexed user, uint256 deltaAccrued, uint256 totalAccrued);
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
user | address | User address |
deltaAccrued | uint256 | Newly accrued amount |
totalAccrued | uint256 | Total accrued amount |
RewardGranted
Emitted when reward is granted to a user
event RewardGranted(address indexed rewardToken, address indexed user, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
user | address | User address |
amount | uint256 | Granted amount |
SupplySpeedUpdated
Emitted when supply speed is updated
event SupplySpeedUpdated(address indexed rewardToken, address indexed mToken, uint256 supplySpeed);
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market token |
supplySpeed | uint256 | New supply speed |
BorrowSpeedUpdated
Emitted when borrow speed is updated
event BorrowSpeedUpdated(address indexed rewardToken, address indexed mToken, uint256 borrowSpeed);
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market token |
borrowSpeed | uint256 | New borrow speed |
OperatorSet
Emitted when operator is updated
event OperatorSet(address indexed oldOperator, address indexed newOperator);
Parameters
| Name | Type | Description |
|---|---|---|
oldOperator | address | Previous operator |
newOperator | address | New operator |
WhitelistedToken
Emitted when token is whitelisted
event WhitelistedToken(address indexed token);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Whitelisted token |
SupplyIndexNotified
Emitted when supply index is notified
event SupplyIndexNotified(address indexed rewardToken, address indexed mToken);
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market token |
BorrowIndexNotified
Emitted when borrow index is notified
event BorrowIndexNotified(address indexed rewardToken, address indexed mToken);
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market token |
IRoles
Title: IRoles
Author: Merge Layers Inc.
Interface for protocol role management
Functions
REBALANCER
Returns REBALANCER role
function REBALANCER() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | REBALANCER role identifier |
REBALANCER_EOA
Returns REBALANCER_EOA role
function REBALANCER_EOA() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | REBALANCER_EOA role identifier |
GUARDIAN_PAUSE
Returns GUARDIAN_PAUSE role
function GUARDIAN_PAUSE() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_PAUSE role identifier |
GUARDIAN_BRIDGE
Returns GUARDIAN_BRIDGE role
function GUARDIAN_BRIDGE() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_BRIDGE role identifier |
GUARDIAN_BORROW_CAP
Returns GUARDIAN_BORROW_CAP role
function GUARDIAN_BORROW_CAP() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_BORROW_CAP role identifier |
GUARDIAN_SUPPLY_CAP
Returns GUARDIAN_SUPPLY_CAP role
function GUARDIAN_SUPPLY_CAP() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_SUPPLY_CAP role identifier |
GUARDIAN_RESERVE
Returns GUARDIAN_RESERVE role
function GUARDIAN_RESERVE() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_RESERVE role identifier |
PROOF_FORWARDER
Returns PROOF_FORWARDER role
function PROOF_FORWARDER() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | PROOF_FORWARDER role identifier |
PROOF_BATCH_FORWARDER
Returns PROOF_BATCH_FORWARDER role
function PROOF_BATCH_FORWARDER() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | PROOF_BATCH_FORWARDER role identifier |
SEQUENCER
Returns SEQUENCER role
function SEQUENCER() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | SEQUENCER role identifier |
PAUSE_MANAGER
Returns PAUSE_MANAGER role
function PAUSE_MANAGER() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | PAUSE_MANAGER role identifier |
CHAINS_MANAGER
Returns CHAINS_MANAGER role
function CHAINS_MANAGER() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | CHAINS_MANAGER role identifier |
GUARDIAN_ORACLE
Returns GUARDIAN_ORACLE role
function GUARDIAN_ORACLE() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_ORACLE role identifier |
GUARDIAN_BLACKLIST
Returns GUARDIAN_BLACKLIST role
function GUARDIAN_BLACKLIST() external view returns (bytes32 role);
Returns
| Name | Type | Description |
|---|---|---|
role | bytes32 | GUARDIAN_BLACKLIST role identifier |
isAllowedFor
Returns allowance status for a contract and a role
function isAllowedFor(address _contract, bytes32 _role) external view returns (bool isAllowed);
Parameters
| Name | Type | Description |
|---|---|---|
_contract | address | The contract address |
_role | bytes32 | The bytes32 role |
Returns
| Name | Type | Description |
|---|---|---|
isAllowed | bool | True if allowed |
Errors
Roles_InputNotValid
Error thrown when input is not valid
error Roles_InputNotValid();
ImErc20
Title: ImErc20
Author: Merge Layers Inc.
Interface for mERC20 token host operations
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 repaymentAmount);
Parameters
| Name | Type | Description |
|---|---|---|
repayAmount | uint256 | The amount to repay, or type(uint256).max for the full outstanding amount |
Returns
| Name | Type | Description |
|---|---|---|
repaymentAmount | uint256 | The actual amount repaid |
repayBehalf
Sender repays a borrow belonging to borrower
function repayBehalf(address borrower, uint256 repayAmount) external returns (uint256 repaymentAmount);
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 |
Returns
| Name | Type | Description |
|---|---|---|
repaymentAmount | uint256 | The actual amount repaid |
liquidate
The sender liquidates the borrowers collateral and transfers seized assets 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
Title: ImErc20Host
Author: Merge Layers Inc.
Interface for host-side mERC20 cross-chain operations
Functions
mintOrBorrowMigration
Mints mTokens during migration without requiring underlying transfer
function mintOrBorrowMigration(bool mint, uint256 amount, address receiver, address borrower, uint256 minAmount)
external;
Parameters
| Name | Type | Description |
|---|---|---|
mint | bool | Mint or borrow |
amount | uint256 | The amount of underlying to be accounted for |
receiver | address | The address that will receive the mTokens or the underlying in case of borrowing |
borrower | address | The address that borrow is executed for |
minAmount | uint256 | The min amount of underlying to be accounted for |
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 |
performExtensionCall
Initiates a withdraw operation
function performExtensionCall(uint256 actionType, uint256 amount, uint32 dstChainId) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
actionType | uint256 | The actionType param (1 - withdraw, 2 - borrow) |
amount | uint256 | The amount to withdraw |
dstChainId | uint32 | The destination chain to recieve funds |
getProofData
Returns the proof data journal
function getProofData(address user, uint32 dstId) external view returns (uint256 dataRoot, uint256 journalHash);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address for the proof |
dstId | uint32 | The destination chain identifier |
Returns
| Name | Type | Description |
|---|---|---|
dataRoot | uint256 | The proof data root |
journalHash | uint256 | The proof journal hash |
Events
AllowedCallerUpdated
Emitted when a user updates allowed callers
event AllowedCallerUpdated(address indexed sender, address indexed caller, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The caller updating permission |
caller | address | The address whose status is updated |
status | bool | Whether the caller is allowed |
mErc20Host_ChainStatusUpdated
Emitted when a chain id whitelist status is updated
event mErc20Host_ChainStatusUpdated(uint32 indexed chainId, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
chainId | uint32 | The chain identifier |
status | bool | Whether the chain is whitelisted |
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
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | The caller on host chain |
srcSender | address | The caller on source chain |
userToLiquidate | address | The user being liquidated |
receiver | address | The receiver of seized collateral |
collateral | address | The collateral market |
srcChainId | uint32 | Source chain identifier |
amount | uint256 | The repay 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
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | The caller on host chain |
srcSender | address | The caller on source chain |
receiver | address | The receiver of minted tokens |
chainId | uint32 | Source chain identifier |
amount | uint256 | The mint amount |
mErc20Host_BorrowExternal
Emitted when a borrow operation is executed
event mErc20Host_BorrowExternal(
address indexed msgSender, address indexed srcSender, uint32 indexed chainId, uint256 amount
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | The caller on host chain |
srcSender | address | The caller on source chain |
chainId | uint32 | Source chain identifier |
amount | uint256 | The borrow 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
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | The caller on host chain |
srcSender | address | The caller on source chain |
position | address | The position being repaid |
chainId | uint32 | Source chain identifier |
amount | uint256 | The repay amount |
mErc20Host_WithdrawExternal
Emitted when a withdrawal is executed
event mErc20Host_WithdrawExternal(
address indexed msgSender, address indexed srcSender, uint32 indexed chainId, uint256 amount
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | The caller on host chain |
srcSender | address | The caller on source chain |
chainId | uint32 | Source chain identifier |
amount | uint256 | The withdrawal amount |
mErc20Host_BorrowOnExtensionChain
Emitted when a borrow operation is triggered for an extension chain
event mErc20Host_BorrowOnExtensionChain(address indexed sender, uint32 dstChainId, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The caller initiating the borrow |
dstChainId | uint32 | Destination chain identifier |
amount | uint256 | The borrow amount |
mErc20Host_WithdrawOnExtensionChain
Emitted when a withdraw operation is triggered for an extension chain
event mErc20Host_WithdrawOnExtensionChain(address indexed sender, uint32 dstChainId, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The caller initiating the withdrawal |
dstChainId | uint32 | Destination chain identifier |
amount | uint256 | The withdrawal amount |
mErc20Host_GasFeeUpdated
Emitted when gas fees are updated for a dst chain
event mErc20Host_GasFeeUpdated(uint32 indexed dstChainId, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | Destination chain identifier |
amount | uint256 | The gas fee amount |
mErc20Host_MintMigration
Emitted when migration mint is performed
event mErc20Host_MintMigration(address indexed receiver, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | Receiver of the migrated tokens |
amount | uint256 | Amount minted |
mErc20Host_BorrowMigration
Emitted when migration borrow is performed
event mErc20Host_BorrowMigration(address indexed borrower, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
borrower | address | Borrower receiving funds |
amount | uint256 | Amount borrowed |
mErc20Host_MigratorUpdated
Emitted when migrator address is updated
event mErc20Host_MigratorUpdated(address indexed migrator);
Parameters
| Name | Type | Description |
|---|---|---|
migrator | address | The new migrator address |
mErc20Host_GasHelperUpdated
Emitted when gas helper address is updated
event mErc20Host_GasHelperUpdated(address indexed helper);
Parameters
| Name | Type | Description |
|---|---|---|
helper | address | The new gas helper address |
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();
mErc20Host_ActionNotAvailable
Thrown when extension action is not valid
error mErc20Host_ActionNotAvailable();
ImTokenOperationTypes
Title: ImTokenOperationTypes
Author: Merge Layers Inc.
Operation types supported by mToken contracts
Enums
OperationType
enum OperationType {
AmountIn,
AmountInHere,
AmountOut,
AmountOutHere,
Seize,
Transfer,
Mint,
Borrow,
Repay,
Redeem,
Liquidate,
Rebalancing
}
ImTokenDelegator
Title: ImTokenDelegator
Author: Merge Layers Inc.
Interface for delegate-capable tokens
Functions
delegate
Non-standard token able to delegate
function delegate(address delegatee) external;
Parameters
| Name | Type | Description |
|---|---|---|
delegatee | address | Address to delegate to |
ImTokenMinimal
Title: ImTokenMinimal
Author: Merge Layers Inc.
Minimal mToken view interface
Functions
name
EIP-20 token name for this token
function name() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | tokenName The token name |
symbol
EIP-20 token symbol for this token
function symbol() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | tokenSymbol The token symbol |
decimals
EIP-20 token decimals for this token
function decimals() external view returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | tokenDecimals The token decimals |
totalSupply
Returns the value of tokens in existence.
function totalSupply() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | supply Total token supply |
totalUnderlying
Returns the amount of underlying tokens
function totalUnderlying() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | underlyingAmount Total underlying amount |
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | balance Token balance of account |
underlying
Returns the underlying address
function underlying() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | underlyingToken The underlying token address |
ImToken
Inherits: ImTokenMinimal
Title: ImToken
Author: Merge Layers Inc.
Core mToken interface with state views and actions
Functions
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 | success 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 | success 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 | success Whether the approval was successful or not |
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 | balance The balance of underlying assets owned by owner |
totalBorrowsCurrent
Returns the total amount of borrows, accounting for interest
function totalBorrowsCurrent() external returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | totalBorrowsCurrentAmount 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 | borrowBalance Current borrow balance |
exchangeRateCurrent
Returns the current exchange rate, with interest accrued
function exchangeRateCurrent() external returns (uint256 exchangeRate);
Returns
| Name | Type | Description |
|---|---|---|
exchangeRate | uint256 | The current exchange rate |
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 |
rolesOperator
Roles manager
function rolesOperator() external view returns (IRoles);
Returns
| Name | Type | Description |
|---|---|---|
<none> | IRoles | roles Roles contract |
admin
Administrator for this contract
function admin() external view returns (address payable adminAddr);
Returns
| Name | Type | Description |
|---|---|---|
adminAddr | address payable | Admin address |
pendingAdmin
Pending administrator for this contract
function pendingAdmin() external view returns (address payable pending);
Returns
| Name | Type | Description |
|---|---|---|
pending | address payable | Pending admin address |
operator
Contract which oversees inter-mToken operations
function operator() external view returns (address operatorAddr);
Returns
| Name | Type | Description |
|---|---|---|
operatorAddr | address | Operator address |
interestRateModel
Model which tells what the current interest rate should be
function interestRateModel() external view returns (address interestModel);
Returns
| Name | Type | Description |
|---|---|---|
interestModel | address | Interest rate model address |
reserveFactorMantissa
Fraction of interest currently set aside for reserves
function reserveFactorMantissa() external view returns (uint256 reserveFactor);
Returns
| Name | Type | Description |
|---|---|---|
reserveFactor | uint256 | Current reserve factor mantissa |
accrualBlockTimestamp
Block timestamp that interest was last accrued at
function accrualBlockTimestamp() external view returns (uint256 timestamp);
Returns
| Name | Type | Description |
|---|---|---|
timestamp | uint256 | Last accrual block timestamp |
borrowIndex
Accumulator of the total earned interest rate since the opening of the market
function borrowIndex() external view returns (uint256 index);
Returns
| Name | Type | Description |
|---|---|---|
index | uint256 | Borrow index |
totalBorrows
Total amount of outstanding borrows of the underlying in this market
function totalBorrows() external view returns (uint256 borrows);
Returns
| Name | Type | Description |
|---|---|---|
borrows | uint256 | Total borrows |
totalReserves
Total amount of reserves of the underlying held in this market
function totalReserves() external view returns (uint256 reserves);
Returns
| Name | Type | Description |
|---|---|---|
reserves | uint256 | Total reserves |
getAccountSnapshot
Returns the snapshot of account details for the given account
function getAccountSnapshot(address account)
external
view
returns (uint256 tokenBalance, uint256 borrowBalance, uint256 exchangeRate);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | The address to query the account snapshot for |
Returns
| Name | Type | Description |
|---|---|---|
tokenBalance | uint256 | Token balance |
borrowBalance | uint256 | Borrow balance |
exchangeRate | uint256 | Exchange rate |
borrowBalanceStored
Returns the stored borrow balance for account, without accruing interest
function borrowBalanceStored(address account) external view returns (uint256 storedBalance);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | The address to query the stored borrow balance for |
Returns
| Name | Type | Description |
|---|---|---|
storedBalance | uint256 | The stored borrow balance |
exchangeRateStored
Returns the stored exchange rate, without accruing interest
function exchangeRateStored() external view returns (uint256 exchangeRateStoredMantissa);
Returns
| Name | Type | Description |
|---|---|---|
exchangeRateStoredMantissa | uint256 | The stored exchange rate |
getCash
Returns the total amount of available cash in the contract
function getCash() external view returns (uint256 cash);
Returns
| Name | Type | Description |
|---|---|---|
cash | uint256 | The total amount of cash |
allowance
Returns the current allowance the spender has from the owner
function allowance(address owner, address spender) external view returns (uint256 allowanceAmount);
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 |
|---|---|---|
allowanceAmount | 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 ownerBalance);
Parameters
| Name | Type | Description |
|---|---|---|
owner | address | The address to query the balance for |
Returns
| Name | Type | Description |
|---|---|---|
ownerBalance | uint256 | The balance of tokens owned by owner |
borrowRatePerBlock
Returns the current borrow rate per block
function borrowRatePerBlock() external view returns (uint256 borrowRate);
Returns
| Name | Type | Description |
|---|---|---|
borrowRate | uint256 | The current borrow rate per block, scaled by 1e18 |
supplyRatePerBlock
Returns the current supply rate per block
function supplyRatePerBlock() external view returns (uint256 supplyRate);
Returns
| Name | Type | Description |
|---|---|---|
supplyRate | uint256 | The current supply rate per block, scaled by 1e18 |
ImTokenGateway
Title: ImTokenGateway
Author: Merge Layers Inc.
Gateway interface for cross-chain mToken operations
Functions
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 |
liquidate
Liquidate a user
function liquidate(address userToLiquidate, uint256 liquidateAmount, address collateral, address receiver)
external
payable;
Parameters
| Name | Type | Description |
|---|---|---|
userToLiquidate | address | The user to liquidate |
liquidateAmount | uint256 | The amount to liquidate |
collateral | address | The collateral address |
receiver | address | The receiver address |
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 |
rolesOperator
Roles
function rolesOperator() external view returns (IRoles roles);
Returns
| Name | Type | Description |
|---|---|---|
roles | IRoles | Roles operator contract |
blacklistOperator
Blacklist operator
function blacklistOperator() external view returns (IBlacklister blacklister);
Returns
| Name | Type | Description |
|---|---|---|
blacklister | IBlacklister | Blacklister contract |
underlying
Returns the address of the underlying token
function underlying() external view returns (address underlyingToken);
Returns
| Name | Type | Description |
|---|---|---|
underlyingToken | address | The address of the underlying token |
isPaused
Returns pause state for operation
function isPaused(ImTokenOperationTypes.OperationType _type) external view returns (bool paused);
Parameters
| Name | Type | Description |
|---|---|---|
_type | ImTokenOperationTypes.OperationType | The operation type |
Returns
| Name | Type | Description |
|---|---|---|
paused | bool | True if paused |
accAmountIn
Returns accumulated amount in per user
function accAmountIn(address user) external view returns (uint256 amountIn);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
amountIn | uint256 | Accumulated amount in |
accAmountOut
Returns accumulated amount out per user
function accAmountOut(address user) external view returns (uint256 amountOut);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
amountOut | uint256 | Accumulated amount out |
getProofData
Returns the proof data journal
function getProofData(address user, uint32 dstId) external view returns (uint256 dataRoot, uint256 journalHash);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
dstId | uint32 | Destination chain identifier |
Returns
| Name | Type | Description |
|---|---|---|
dataRoot | uint256 | The proof data root |
journalHash | uint256 | The proof journal hash |
gasFee
Returns the gas fee for Linea
function gasFee() external view returns (uint256 fee);
Returns
| Name | Type | Description |
|---|---|---|
fee | uint256 | Gas fee amount |
Events
AllowedCallerUpdated
Emitted when a user updates allowed callers
event AllowedCallerUpdated(address indexed sender, address indexed caller, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The caller updating permissions |
caller | address | The address whose status is updated |
status | bool | Whether the caller is allowed |
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
);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Sender on source chain |
receiver | address | Receiver on destination |
accAmountIn | uint256 | Accumulated amount in |
accAmountOut | uint256 | Accumulated amount out |
amount | uint256 | Supplied amount |
srcChainId | uint32 | Source chain ID |
dstChainId | uint32 | Destination chain ID |
lineaMethodSelector | bytes4 | Linea method selector |
mTokenGateway_Liquidate
Emitted when a liquidate operation is initiated
event mTokenGateway_Liquidate(
address indexed from,
address indexed receiver,
uint256 amount,
uint32 srcChainId,
uint32 dstChainId,
address userToLiquidate,
address collateral
);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Sender on source chain |
receiver | address | Receiver of seized collateral |
amount | uint256 | Liquidation amount |
srcChainId | uint32 | Source chain ID |
dstChainId | uint32 | Destination chain ID |
userToLiquidate | address | User being liquidated |
collateral | address | Collateral market address |
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
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | Sender on host chain |
srcSender | address | Sender on source chain |
receiver | address | Receiver of funds |
accAmountIn | uint256 | Accumulated amount in |
accAmountOut | uint256 | Accumulated amount out |
amount | uint256 | Amount extracted |
srcChainId | uint32 | Source chain ID |
dstChainId | uint32 | Destination chain ID |
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
);
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | Sender on host chain |
srcSender | address | Sender on source chain |
receiver | address | Receiver of funds |
accAmountIn | uint256 | Accumulated amount in |
accAmountOut | uint256 | Accumulated amount out |
amount | uint256 | Amount skipped |
srcChainId | uint32 | Source chain ID |
dstChainId | uint32 | Destination chain ID |
mTokenGateway_GasFeeUpdated
Emitted when the gas fee is updated
event mTokenGateway_GasFeeUpdated(uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | New gas fee amount |
mTokenGateway_PausedState
Emitted when pause state changes
event mTokenGateway_PausedState(ImTokenOperationTypes.OperationType indexed _type, bool _status);
Parameters
| Name | Type | Description |
|---|---|---|
_type | ImTokenOperationTypes.OperationType | Operation type paused/unpaused |
_status | bool | Pause status |
ZkVerifierUpdated
Emitted when zk verifier is updated
event ZkVerifierUpdated(address indexed oldVerifier, address indexed newVerifier);
Parameters
| Name | Type | Description |
|---|---|---|
oldVerifier | address | Previous verifier |
newVerifier | address | New verifier |
mTokenGateway_UserWhitelisted
Emitted when user whitelist status changes
event mTokenGateway_UserWhitelisted(address indexed user, bool status);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
status | bool | Whitelist status |
mTokenGateway_WhitelistEnabled
Emitted when whitelist is enabled
event mTokenGateway_WhitelistEnabled();
mTokenGateway_WhitelistDisabled
Emitted when whitelist is disabled
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();
mTokenGateway_UserBlacklisted
Thrown when user is blacklisted
error mTokenGateway_UserBlacklisted();
Contents
- Bytes32AddressLib
- BytesLib
- CREATE3
- CommonLib
- IHypernativeFirewall
- HypernativeFirewallProtected
- IToken
- SafeApprove
- mTokenProofDecoderLib
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);
CommonLib
Title: CommonLib
Author: Merge Layers Inc.
Shared helper utilities for validation and math
Functions
checkHostToExtension
Checks a host to extension call for validity
function checkHostToExtension(
uint256 amount,
uint32 dstChainId,
uint256 msgValue,
mapping(uint32 => bool) storage allowedChains,
IGasFeesHelper gasHelper
) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount being transferred |
dstChainId | uint32 | Destination chain id |
msgValue | uint256 | Message value provided |
allowedChains | mapping(uint32 => bool) | Mapping of allowed chain ids |
gasHelper | IGasFeesHelper | Gas helper contract |
checkLengthMatch
Ensures two lengths match
function checkLengthMatch(uint256 l1, uint256 l2) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
l1 | uint256 | First length |
l2 | uint256 | Second length |
checkLengthMatch
Ensures three lengths match
function checkLengthMatch(uint256 l1, uint256 l2, uint256 l3) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
l1 | uint256 | First length |
l2 | uint256 | Second length |
l3 | uint256 | Third length |
computeSum
Computes sum of an array
function computeSum(uint256[] calldata values) internal pure returns (uint256 sum);
Parameters
| Name | Type | Description |
|---|---|---|
values | uint256[] | Array of values |
Returns
| Name | Type | Description |
|---|---|---|
sum | uint256 | Total sum |
Errors
CommonLib_LengthMismatch
Thrown when array lengths mismatch
error CommonLib_LengthMismatch();
AmountNotValid
Thrown when amount is invalid
error AmountNotValid();
ChainNotValid
Thrown when chain id is not allowed
error ChainNotValid();
NotEnoughGasFee
Thrown when provided gas fee is insufficient
error NotEnoughGasFee();
IHypernativeFirewall
Title: IHypernativeFirewall
Author: Merge Layers Inc.
Interface for the HypernativeFirewall contract
Functions
register
Registers an account with the firewall
function register(address account, bool isStrictMode) external;
Parameters
| Name | Type | Description |
|---|---|---|
account | address | The account to register |
isStrictMode | bool | The strict mode |
validateBlacklistedAccountInteraction
Validates the blacklisted account interaction
function validateBlacklistedAccountInteraction(address sender) external;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The sender of the transaction |
validateForbiddenAccountInteraction
Validates the forbidden account interaction
function validateForbiddenAccountInteraction(address sender) external view;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The sender of the transaction |
validateForbiddenContextInteraction
Validates the forbidden context interaction
function validateForbiddenContextInteraction(address origin, address sender) external view;
Parameters
| Name | Type | Description |
|---|---|---|
origin | address | The origin of the transaction |
sender | address | The sender of the transaction |
HypernativeFirewallProtected
Title: HypernativeFirewallProtected
Author: Merge Layers Inc.
Abstract contract that provides firewall protection for the contract.
Inherited from Hypernative and refactored it for our needs, but without changing the core logic.
State Variables
HYPERNATIVE_ORACLE_STORAGE_SLOT
Storage slot for the firewall address
bytes32 private constant HYPERNATIVE_ORACLE_STORAGE_SLOT =
bytes32(uint256(keccak256("eip1967.hypernative.firewall")) - 1)
HYPERNATIVE_ADMIN_STORAGE_SLOT
Storage slot for the firewall admin address
bytes32 private constant HYPERNATIVE_ADMIN_STORAGE_SLOT =
bytes32(uint256(keccak256("eip1967.hypernative.admin")) - 1)
HYPERNATIVE_MODE_STORAGE_SLOT
Storage slot for the firewall strict mode
bytes32 private constant HYPERNATIVE_MODE_STORAGE_SLOT =
bytes32(uint256(keccak256("eip1967.hypernative.is_strict_mode")) - 1)
Functions
onlyFirewallApproved
Modifier to restrict access to only approved firewall addresses
modifier onlyFirewallApproved() ;
onlyFirewallApprovedAllowEOA
Modifier to restrict access to only approved firewall addresses and EOAs
modifier onlyFirewallApprovedAllowEOA() ;
onlyNotBlacklistedEOA
Modifier to restrict access to only not blacklisted EOAs
modifier onlyNotBlacklistedEOA() ;
onlyFirewallAdmin
Modifier to restrict access to only the firewall admin
modifier onlyFirewallAdmin() ;
firewallRegister
Function to register an account with the firewall
function firewallRegister(address _account) public virtual;
Parameters
| Name | Type | Description |
|---|---|---|
_account | address | The account to register |
setFirewall
Function to set the firewall
Admin only function, sets new firewall admin. set to address(0) to revoke firewall
function setFirewall(address _firewall) public onlyFirewallAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_firewall | address | The new firewall address |
setIsStrictMode
Function to set the strict mode
function setIsStrictMode(bool _mode) public onlyFirewallAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_mode | bool | The strict mode |
changeFirewallAdmin
Function to change the firewall admin
function changeFirewallAdmin(address _newAdmin) public onlyFirewallAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_newAdmin | address | The new firewall admin address |
hypernativeFirewallAdmin
Function to get the firewall admin
function hypernativeFirewallAdmin() public view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The firewall admin address |
_initHypernativeFirewall
Internal function to initialize the firewall
function _initHypernativeFirewall(address _firewall, address _admin) internal;
Parameters
| Name | Type | Description |
|---|---|---|
_firewall | address | The firewall address |
_admin | address | The firewall admin address |
_changeFirewallAdmin
Internal function to change the firewall admin
function _changeFirewallAdmin(address _newAdmin) internal;
Parameters
| Name | Type | Description |
|---|---|---|
_newAdmin | address | The new firewall admin address |
_setAddressBySlot
Internal function to set the address in the slot
function _setAddressBySlot(bytes32 slot, address newAddress) internal;
Parameters
| Name | Type | Description |
|---|---|---|
slot | bytes32 | The slot to set the address in |
newAddress | address | The address to set in the slot |
_setValueBySlot
Internal function to set the value in the slot
function _setValueBySlot(bytes32 _slot, uint256 _value) internal;
Parameters
| Name | Type | Description |
|---|---|---|
_slot | bytes32 | The slot to set the value in |
_value | uint256 | The value to set in the slot |
_getAddressBySlot
Internal function to get the address from the slot
function _getAddressBySlot(bytes32 slot) internal view returns (address addr);
Parameters
| Name | Type | Description |
|---|---|---|
slot | bytes32 | The slot to get the address from |
Returns
| Name | Type | Description |
|---|---|---|
addr | address | The address from the slot |
_getValueBySlot
Internal function to get the value from the slot
function _getValueBySlot(bytes32 _slot) internal view returns (uint256 value);
Parameters
| Name | Type | Description |
|---|---|---|
_slot | bytes32 | The slot to get the value from |
Returns
| Name | Type | Description |
|---|---|---|
value | uint256 | The value from the slot |
_hypernativeFirewallIsStrictMode
Internal function to get the strict mode
function _hypernativeFirewallIsStrictMode() private view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | The strict mode |
_hypernativeFirewall
Internal function to get the firewall address
function _hypernativeFirewall() private view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The firewall address |
Events
FirewallAdminChanged
Emitted when the firewall admin is changed
event FirewallAdminChanged(address indexed previousAdmin, address indexed newAdmin);
Parameters
| Name | Type | Description |
|---|---|---|
previousAdmin | address | The previous firewall admin address |
newAdmin | address | The new firewall admin address |
FirewallAddressChanged
Emitted when the firewall address is changed
event FirewallAddressChanged(address indexed previousFirewall, address indexed newFirewall);
Parameters
| Name | Type | Description |
|---|---|---|
previousFirewall | address | The previous firewall address |
newFirewall | address | The new firewall address |
Errors
HypernativeFirewallProtected_CallerNotEOA
Thrown when the caller is not an EOA
error HypernativeFirewallProtected_CallerNotEOA();
HypernativeFirewallProtected_CallerNotFirewallAdmin
Thrown when the caller is not the firewall admin
error HypernativeFirewallProtected_CallerNotFirewallAdmin();
HypernativeFirewallProtected_AddressNotValid
Thrown when the address is not valid
error HypernativeFirewallProtected_AddressNotValid();
IToken
Title: Minimal ERC20 approve interface
Author: Merge Layers Inc.
Exposes approve to perform safe allowance updates
Functions
approve
Approves spender for an allowance amount
function approve(address spender, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
spender | address | Address allowed to spend |
amount | uint256 | Allowance amount |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if approve succeeded |
SafeApprove
Title: SafeApprove
Author: Merge Layers Inc.
Library for safely setting ERC20 approvals
Functions
safeApprove
Safely sets allowance to zero then desired value
function safeApprove(address token, address to, uint256 value) internal;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token to approve |
to | address | Spender address |
value | uint256 | New allowance to set |
Errors
SafeApprove_NoContract
Thrown when target is not a contract
error SafeApprove_NoContract();
SafeApprove_Failed
Thrown when an approve call fails
error SafeApprove_Failed();
mTokenProofDecoderLib
Title: mTokenProofDecoderLib
Author: Merge Layers Inc.
Utility library for encoding and decoding mToken journals
State Variables
ENTRY_SIZE
Encoded journal entry size in bytes
uint256 public constant ENTRY_SIZE = 113
Functions
decodeJournal
Decodes encoded journal data into fields
function decodeJournal(bytes memory journalData)
internal
pure
returns (
address sender,
address market,
uint256 accAmountIn,
uint256 accAmountOut,
uint32 chainId,
uint32 dstChainId,
bool l1Inclusion
);
Parameters
| Name | Type | Description |
|---|---|---|
journalData | bytes | Packed journal bytes |
Returns
| Name | Type | Description |
|---|---|---|
sender | address | Journal sender |
market | address | Market address |
accAmountIn | uint256 | Accumulated amount in |
accAmountOut | uint256 | Accumulated amount out |
chainId | uint32 | Source chain id |
dstChainId | uint32 | Destination chain id |
l1Inclusion | bool | Whether L1 inclusion is required |
encodeJournal
Encodes journal fields into packed bytes
function encodeJournal(
address sender,
address market,
uint256 accAmountIn,
uint256 accAmountOut,
uint32 chainId,
uint32 dstChainId,
bool l1Inclusion
) internal pure returns (bytes memory);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | Journal sender |
market | address | Market address |
accAmountIn | uint256 | Accumulated amount in |
accAmountOut | uint256 | Accumulated amount out |
chainId | uint32 | Source chain id |
dstChainId | uint32 | Destination chain id |
l1Inclusion | bool | Whether L1 inclusion is required |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes | Packed journal bytes |
Errors
mTokenProofDecoderLib_ChainNotFound
Thrown when chain is not found
error mTokenProofDecoderLib_ChainNotFound();
mTokenProofDecoderLib_InvalidLength
Thrown when journal length is invalid
error mTokenProofDecoderLib_InvalidLength();
mTokenProofDecoderLib_InvalidInclusion
Thrown when L1 inclusion flag is invalid
error mTokenProofDecoderLib_InvalidInclusion();
Contents
- extension
- host
- BatchSubmitter
- mErc20
- mErc20Immutable
- mErc20Upgradable
- mToken
- mTokenConfiguration
- mTokenStorage
Contents
mTokenGateway
Inherits: OwnableUpgradeable, ImTokenGateway, ImTokenOperationTypes, HypernativeFirewallProtected
Title: mTokenGateway
Author: Merge Layers Inc.
Gateway contract for mToken operations
State Variables
LINEA_CHAIN_ID
Linea chain ID
uint32 private constant LINEA_CHAIN_ID = 59144
rolesOperator
Roles
IRoles public rolesOperator
blacklistOperator
Blacklist operator
IBlacklister public blacklistOperator
verifier
The ZkVerifier contract
IZkVerifier public verifier
paused
Mapping of operation types to pause status
mapping(OperationType operationType => bool paused) public paused
underlying
Returns the address of the underlying token
address public underlying
accAmountIn
Mapping of accumulated amounts in
mapping(address account => uint256 amount) public accAmountIn
accAmountOut
Mapping of accumulated amounts out
mapping(address account => uint256 amount) public accAmountOut
allowedCallers
Mapping of allowed callers
mapping(address caller => mapping(address target => bool allowed)) public allowedCallers
userWhitelisted
Mapping of whitelisted users
mapping(address user => bool whitelisted) public userWhitelisted
whitelistEnabled
Whether whitelist is enabled
bool public whitelistEnabled
gasFee
Gas fee required for supplyOnHost
uint256 public gasFee
__gap
uint256[50] private __gap
Functions
notPaused
Modifier to restrict access to only allowed users
modifier notPaused(OperationType _type) ;
Parameters
| Name | Type | Description |
|---|---|---|
_type | OperationType | The operation type |
onlyAllowedUser
Modifier to restrict access to only allowed users
modifier onlyAllowedUser(address user) ;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
ifNotBlacklisted
Modifier to restrict access to only not blacklisted users
modifier ifNotBlacklisted(address user) ;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
liquidateChecks
Modifier to check liquidate conditions
modifier liquidateChecks() ;
constructor
Disables initializers on implementation
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
initialize
Initializes the gateway
function initialize(
address payable _owner,
address _underlying,
address _roles,
address _blacklister,
address zkVerifier_
) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
_owner | address payable | Owner address |
_underlying | address | Underlying token |
_roles | address | Roles contract |
_blacklister | address | Blacklister contract |
zkVerifier_ | address | ZK verifier |
initFirewall
Initializes the firewall configuration
function initFirewall(address _firewall) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
_firewall | address | Firewall address to set |
setBlacklister
Sets the blacklister contract
function setBlacklister(address _blacklister) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
_blacklister | address | Address of the blacklister |
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 state |
enableWhitelist
Enable user whitelist
function enableWhitelist() external onlyOwner;
disableWhitelist
Disable user whitelist
function disableWhitelist() external onlyOwner;
setPaused
function setPaused(OperationType _type, bool state) external override;
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 |
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)
ifNotBlacklisted(msg.sender)
ifNotBlacklisted(receiver)
onlyFirewallApproved;
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 |
liquidate
Liquidate a user
function liquidate(address userToLiquidate, uint256 liquidateAmount, address collateral, address receiver)
external
payable
override
liquidateChecks
ifNotBlacklisted(receiver);
Parameters
| Name | Type | Description |
|---|---|---|
userToLiquidate | address | The user to liquidate |
liquidateAmount | uint256 | The amount to liquidate |
collateral | address | The collateral address |
receiver | address | The receiver address |
outHere
Extract tokens
function outHere(bytes calldata journalData, bytes calldata seal, uint256[] calldata amounts, address receiver)
external
notPaused(OperationType.AmountOutHere)
ifNotBlacklisted(msg.sender)
ifNotBlacklisted(receiver)
onlyFirewallApproved;
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 |
isPaused
function isPaused(OperationType _type) external view returns (bool);
getProofData
Returns the proof data journal
function getProofData(address user, uint32) external view returns (uint256, uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
<none> | uint32 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | dataRoot The proof data root |
<none> | uint256 | journalHash The proof journal hash |
firewallRegister
Registers an account in the firewall
function firewallRegister(address _account) public override(HypernativeFirewallProtected);
Parameters
| Name | Type | Description |
|---|---|---|
_account | address | Account to register |
_takeIn
Handles inbound transfers and accounting
function _takeIn(address asset, uint256 amount, address receiver) private;
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | Asset address |
amount | uint256 | Amount to transfer |
receiver | address | Receiver address |
_outHere
Processes an outgoing transfer based on journal data
function _outHere(bytes memory journalData, uint256 amount, address receiver) private;
Parameters
| Name | Type | Description |
|---|---|---|
journalData | bytes | Encoded journal payload |
amount | uint256 | Amount to transfer |
receiver | address | Receiver address override |
_verifyProof
Verifies proof data and inclusion constraints
function _verifyProof(bytes calldata journalData, bytes calldata seal) private view;
Parameters
| Name | Type | Description |
|---|---|---|
journalData | bytes | Encoded journals |
seal | bytes | Proof seal data |
_checkSender
Validates sender permissions for proof forwarding
function _checkSender(address msgSender, address srcSender) private view;
Parameters
| Name | Type | Description |
|---|---|---|
msgSender | address | Caller address |
srcSender | address | Source sender encoded in journal |
_getSequencerRole
Returns sequencer role identifier
function _getSequencerRole() private view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role id |
_getBatchProofForwarderRole
Returns batch proof forwarder role identifier
function _getBatchProofForwarderRole() private view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role id |
_getProofForwarderRole
Returns proof forwarder role identifier
function _getProofForwarderRole() private view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role id |
_isAllowedFor
Checks if sender has a specific role
function _isAllowedFor(address _sender, bytes32 role) private view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
_sender | address | Sender address |
role | bytes32 | Role to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if allowed |
Contents
mErc20Host
Inherits: mErc20Upgradable, ImErc20Host, ImTokenOperationTypes
Title: mErc20Host
Author: Merge Layers Inc.
Host contract for mErc20 tokens
State Variables
acc
Mapping of chain IDs to accumulated amounts
mapping(uint32 chainId => Accumulated accumulated) internal acc
allowedCallers
Mapping of allowed callers
mapping(address caller => mapping(address target => bool allowed)) public allowedCallers
allowedChains
Mapping of allowed chains
mapping(uint32 chainId => bool allowed) public allowedChains
verifier
The ZkVerifier contract
IZkVerifier public verifier
gasHelper
The gas fees helper contract
IGasFeesHelper public gasHelper
migrator
Migrator address
address public migrator
__gap
uint256[50] private __gap
Functions
onlyMigrator
Modifier to restrict access to migrator only
modifier onlyMigrator() ;
initialize
Initializes the new money market
function initialize(
address underlying_,
address operator_,
address interestRateModel_,
uint256 initialExchangeRateMantissa_,
// note: these have to remain as 'memory' to avoid stack-depth issues
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 | The IRoles address |
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 |
setGasHelper
Sets the gas fees helper address
function setGasHelper(address _helper) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_helper | address | The new helper address |
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 |
performExtensionCall
Initiates a withdraw operation
function performExtensionCall(uint256 actionType, uint256 amount, uint32 dstChainId) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
actionType | uint256 | The actionType param (1 - withdraw, 2 - borrow) |
amount | uint256 | The amount to withdraw |
dstChainId | uint32 | The destination chain to recieve funds |
mintOrBorrowMigration
Mints mTokens during migration without requiring underlying transfer
function mintOrBorrowMigration(bool isMint, uint256 amount, address receiver, address borrower, uint256 minAmount)
external
onlyMigrator;
Parameters
| Name | Type | Description |
|---|---|---|
isMint | bool | |
amount | uint256 | The amount of underlying to be accounted for |
receiver | address | The address that will receive the mTokens or the underlying in case of borrowing |
borrower | address | The address that borrow is executed for |
minAmount | uint256 | The min amount of underlying to be accounted for |
getProofData
Returns the proof data journal
function getProofData(address user, uint32 dstId) external view returns (uint256, uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address for the proof |
dstId | uint32 | The destination chain identifier |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | dataRoot The proof data root |
<none> | uint256 | journalHash The proof journal hash |
_liquidateExternal
Processes a single liquidateExternal call from decoded journal
function _liquidateExternal(
bytes memory singleJournal,
address userToLiquidate,
uint256 liquidateAmount,
address collateral,
address receiver
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
singleJournal | bytes | Encoded journal entry |
userToLiquidate | address | Account to be liquidated |
liquidateAmount | uint256 | Amount to liquidate |
collateral | address | Collateral address to seize |
receiver | address | Receiver of seized collateral |
_mintExternal
Processes a single mintExternal call from decoded journal
function _mintExternal(bytes memory singleJournal, uint256 mintAmount, uint256 minAmountOut, address receiver)
internal;
Parameters
| Name | Type | Description |
|---|---|---|
singleJournal | bytes | Encoded journal entry |
mintAmount | uint256 | Amount to mint |
minAmountOut | uint256 | Minimum amount out allowed |
receiver | address | Receiver address |
_repayExternal
Processes a single repayExternal call from decoded journal
function _repayExternal(bytes memory singleJournal, uint256 repayAmount, address receiver) internal;
Parameters
| Name | Type | Description |
|---|---|---|
singleJournal | bytes | Encoded journal entry |
repayAmount | uint256 | Amount to repay |
receiver | address | Receiver address |
_checkOutflow
Validates outflow limits via defender
function _checkOutflow(uint256 amount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount to check |
_onlyAdminOrRole
Ensures caller is admin or has specific role
function _onlyAdminOrRole(bytes32 _role) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
_role | bytes32 | Role identifier to check |
_checkJournalData
Performs basic proof call checks
function _checkJournalData(uint32 dstChainId, uint32 chainId, address market, address sender) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | Destination chain id |
chainId | uint32 | Source chain id |
market | address | Market address encoded in proof |
sender | address | Sender extracted from proof |
_isAllowedFor
Checks if sender has specified role
function _isAllowedFor(address _sender, bytes32 role) internal view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
_sender | address | Address to check |
role | bytes32 | Role identifier |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if allowed |
_getChainsManagerRole
Retrieves chains manager role id
function _getChainsManagerRole() internal view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role identifier |
_getProofForwarderRole
Retrieves proof forwarder role id
function _getProofForwarderRole() internal view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role identifier |
_getBatchProofForwarderRole
Retrieves batch proof forwarder role id
function _getBatchProofForwarderRole() internal view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role identifier |
_getSequencerRole
Retrieves sequencer role id
function _getSequencerRole() internal view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Role identifier |
_verifyProof
Verifies proof data and checks inclusion constraints
function _verifyProof(bytes calldata journalData, bytes calldata seal) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
journalData | bytes | Encoded journal data |
seal | bytes | Zk proof seal |
_decodeJournals
Decodes encoded journals data
function _decodeJournals(bytes calldata data) internal pure returns (bytes[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
data | bytes | Encoded journal data |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes[] | Decoded journals array |
Structs
Accumulated
Struct for accumulated amounts per chain
struct Accumulated {
mapping(address chain => uint256 amount) inPerChain;
mapping(address chain => uint256 amount) outPerChain;
}
BatchSubmitter
Inherits: Ownable
Title: BatchSubmitter
Author: Merge Layers Inc.
Contract for batch processing multiple operations
State Variables
MINT_SELECTOR
The function selector for the supported mintExternal operation
bytes4 internal constant MINT_SELECTOR = ImErc20Host.mintExternal.selector
REPAY_SELECTOR
The function selector for the supported repayExternal operation
bytes4 internal constant REPAY_SELECTOR = ImErc20Host.repayExternal.selector
OUT_HERE_SELECTOR
The function selector for the supported outHere operation
bytes4 internal constant OUT_HERE_SELECTOR = ImTokenGateway.outHere.selector
LIQUIDATE_SELECTOR
The function selector for the supported liquidateExternal operation
bytes4 internal constant LIQUIDATE_SELECTOR = ImErc20Host.liquidateExternal.selector
ROLES_OPERATOR
The roles contract for access control
IRoles public immutable ROLES_OPERATOR
verifier
The ZkVerifier contract
IZkVerifier public verifier
Functions
constructor
Constructor
constructor(address _roles, address _zkVerifier, address owner_) Ownable(owner_);
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | The roles contract address |
_zkVerifier | address | The ZkVerifier contract address |
owner_ | address | The owner address |
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;
Parameters
| Name | Type | Description |
|---|---|---|
data | BatchProcessMsg | The batch process message data |
_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 emitted when batch process fails
event BatchProcessFailed(
bytes32 initHash,
address receiver,
address mToken,
uint256 amount,
uint256 minAmountOut,
bytes4 selector,
bytes reason
);
Parameters
| Name | Type | Description |
|---|---|---|
initHash | bytes32 | The initialization hash |
receiver | address | The receiver address |
mToken | address | The mToken address |
amount | uint256 | The amount |
minAmountOut | uint256 | The minimum amount out |
selector | bytes4 | The function selector |
reason | bytes | The failure reason |
BatchProcessSuccess
Event emitted when batch process succeeds
event BatchProcessSuccess(
bytes32 initHash, address receiver, address mToken, uint256 amount, uint256 minAmountOut, bytes4 selector
);
Parameters
| Name | Type | Description |
|---|---|---|
initHash | bytes32 | The initialization hash |
receiver | address | The receiver address |
mToken | address | The mToken address |
amount | uint256 | The amount |
minAmountOut | uint256 | The minimum amount out |
selector | bytes4 | The function selector |
ZkVerifierUpdated
Event emitted when ZkVerifier is updated
event ZkVerifierUpdated(address indexed oldVerifier, address indexed newVerifier);
Parameters
| Name | Type | Description |
|---|---|---|
oldVerifier | address | The old verifier address |
newVerifier | address | The new verifier address |
Errors
BatchSubmitter_CallerNotAllowed
Error thrown when caller is not allowed
error BatchSubmitter_CallerNotAllowed();
BatchSubmitter_JournalNotValid
Error thrown when journal is not valid
error BatchSubmitter_JournalNotValid();
BatchSubmitter_InvalidSelector
Error thrown when selector is invalid
error BatchSubmitter_InvalidSelector();
BatchSubmitter_AddressNotValid
Error thrown when address is not valid
error BatchSubmitter_AddressNotValid();
Structs
BatchProcessMsg
Parameters used to process a batch of operations
struct BatchProcessMsg {
address[] receivers;
bytes journalData;
bytes seal;
address[] mTokens;
uint256[] amounts;
uint256[] minAmountsOut;
bytes4[] selectors;
bytes32[] initHashes;
uint256 startIndex;
address[] userToLiquidate;
address[] collateral;
}
Properties
| Name | Type | Description |
|---|---|---|
receivers | address[] | Funds receivers |
journalData | bytes | Encoded journal data |
seal | bytes | Seal data for verification |
mTokens | address[] | Array of mToken addresses |
amounts | uint256[] | Array of amounts for each operation |
minAmountsOut | uint256[] | Array of minimum output amounts |
selectors | bytes4[] | Array of function selectors for each operation |
initHashes | bytes32[] | Array of initial hashes for journals |
startIndex | uint256 | Start index for processing journals |
userToLiquidate | address[] | Array of users to liquidate (for liquidateExternal operations) |
collateral | address[] | Array of collateral addresses (for liquidateExternal operations) |
mErc20
Title: Malda's mErc20 Contract
Author: Merge Layers Inc.
mTokens which wrap an EIP-20 underlying
State Variables
underlying
Underlying asset for this mToken
address public underlying
Functions
sweepToken
A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
function sweepToken(IERC20 token, uint256 amount) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
token | IERC20 | The address of the ERC-20 token to sweep |
amount | uint256 | The amount of tokens 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;
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | repaymentAmount The actual amount repaid |
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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | repaymentAmount The actual amount repaid |
liquidate
The sender liquidates the borrowers collateral and transfers seized assets 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 |
_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 |
_doTransferIn
Performs a transfer in, reverting upon failure
function _doTransferIn(address from, uint256 amount) internal virtual override returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Sender address |
amount | uint256 | Amount to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Amount actually transferred to the protocol |
_doTransferOut
Performs a transfer out to a recipient
function _doTransferOut(address payable to, uint256 amount) internal virtual override;
Parameters
| Name | Type | Description |
|---|---|---|
to | address payable | Recipient address |
amount | uint256 | Amount to transfer |
_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 |
Errors
mErc20_TokenNotValid
Error thrown when token is not valid
error mErc20_TokenNotValid();
mErc20Immutable
Inherits: mErc20
Title: mErc20Immutable
Author: Merge Layers Inc.
Immutable mErc20 contract
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 |
Errors
mErc20Immutable_AdminNotValid
Error thrown when admin is not valid
error mErc20Immutable_AdminNotValid();
mErc20Upgradable
Inherits: mErc20, Initializable
Title: Upgradable mErc20
Author: Merge Layers Inc.
Upgradable flavor of mErc20 with initializer support
Functions
constructor
Disables initializers on deployment
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 | Address of the administrator |
Errors
mErc20Upgradable_AdminNotValid
Error thrown when the admin is not valid
error mErc20Upgradable_AdminNotValid();
mToken
Inherits: mTokenConfiguration, ReentrancyGuard
Title: Core mToken logic
Author: Merge Layers Inc.
Base ERC-20 compatible lending token logic
Functions
constructor
Sets initial borrow rate max mantissa
constructor() ;
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 | success 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 | success 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 | success 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 | totalBorrowsCurrentAmount 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 | borrowBalance Current borrow balance |
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 |
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 | balance The balance of underlying assets owned by owner |
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 | allowanceAmount 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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | balance Token balance of account |
getAccountSnapshot
Returns the snapshot of account details for the given account
function getAccountSnapshot(address account)
external
view
override
returns (uint256 tokenBalance, uint256 borrowBalance, uint256 exchangeRate);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | The address to query the account snapshot for |
Returns
| Name | Type | Description |
|---|---|---|
tokenBalance | uint256 | Token balance |
borrowBalance | uint256 | Borrow balance |
exchangeRate | uint256 | Exchange rate |
borrowRatePerBlock
Returns the current borrow rate per block
function borrowRatePerBlock() external view override returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | borrowRate 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 | supplyRate 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 | storedBalance 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 | cash 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 | exchangeRateStoredMantissa The stored exchange rate |
exchangeRateCurrent
Returns the current exchange rate, with interest accrued
function exchangeRateCurrent() public override nonReentrant returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | exchangeRate The current exchange rate |
_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 |
_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 | The 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 |
Returns
| Name | Type | Description |
|---|---|---|
underlyingAmount | uint256 | Amount of underlying redeemed |
_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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | actualRepay Amount actually repaid |
_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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | actualRepay Amount actually repaid |
_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. It's 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 |
_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 | borrowBalance Borrow balance with interest applied |
__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 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Amount actually repaid |
__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 | Borrower address |
receiver | address payable | Receiver address |
borrowAmount | uint256 | The amount of the underlying asset to borrow |
doTransfer | bool | If an actual transfer should be performed |
__redeem
Executes redemption and performs transfers
function __redeem(address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool doTransfer)
private
returns (uint256 redeemAmount);
Parameters
| Name | Type | Description |
|---|---|---|
redeemer | address payable | Address redeeming |
redeemTokensIn | uint256 | Number of tokens to redeem (if non-zero) |
redeemAmountIn | uint256 | Underlying amount to redeem (if non-zero) |
doTransfer | bool | If an actual transfer should be performed |
Returns
| Name | Type | Description |
|---|---|---|
redeemAmount | uint256 | Underlying redeemed |
__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 |
__calculateSeizeTokens
Calculates seize token amount for liquidation
function __calculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint256 actualRepayAmount)
private
view
returns (uint256 seizeTokens);
Parameters
| Name | Type | Description |
|---|---|---|
mTokenBorrowed | address | The market of the borrowed asset |
mTokenCollateral | address | The market of the collateral asset |
actualRepayAmount | uint256 | Actual amount repaid |
Returns
| Name | Type | Description |
|---|---|---|
seizeTokens | uint256 | Amount of collateral tokens to seize |
mTokenConfiguration
Inherits: mTokenStorage
Title: mTokenConfiguration
Author: Merge Layers Inc.
Configuration helpers for mToken markets
Functions
onlyAdmin
modifier onlyAdmin() ;
setOperator
Sets a new Operator for the market
function setOperator(address _operator) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_operator | address | The new operator address |
setRolesOperator
Sets a new Roles operator for the market
function setRolesOperator(address _roles) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | The roles contract address |
setInterestRateModel
Accrues interest and updates the interest rate model using _setInterestRateModelFresh
function setInterestRateModel(address newInterestRateModel) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
newInterestRateModel | address | The new interest rate model to use |
setBorrowRateMaxMantissa
Sets the maximum borrow rate mantissa
function setBorrowRateMaxMantissa(uint256 maxMantissa) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
maxMantissa | uint256 | The new max mantissa |
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;
Parameters
| Name | Type | Description |
|---|---|---|
newReserveFactorMantissa | uint256 | The new reserve factor mantissa |
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
Sets the Operator contract address
function _setOperator(address _operator) internal;
Parameters
| Name | Type | Description |
|---|---|---|
_operator | address | The operator address |
mTokenStorage
Inherits: ImToken, ExponentialNoError
Title: mTokenStorage
Author: Merge Layers Inc.
Storage contract for mToken
State Variables
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
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
accountBorrows
Mapping of account addresses to borrow snapshots
mapping(address account => BorrowSnapshot snapshot) internal accountBorrows
accountTokens
Mapping of account addresses to token balances
mapping(address account => uint256 tokens) internal accountTokens
transferAllowances
Mapping of owner to spender to allowance amount
mapping(address owner => mapping(address spender => uint256 amount)) internal transferAllowances
initialExchangeRateMantissa
Initial exchange rate used when minting the first mTokens (used when totalSupply = 0)
uint256 internal initialExchangeRateMantissa
__gap
uint256[50] private __gap
Functions
accrueInterest
Accrues interest on the contract's outstanding loans
function accrueInterest() external virtual;
_accrueInterest
Accrues interest up to the current timestamp
function _accrueInterest() internal;
_doTransferIn
Performs a transfer in, reverting upon failure
function _doTransferIn(address from, uint256 amount) internal virtual returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Sender address |
amount | uint256 | Amount to transfer in |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Amount actually transferred to the protocol |
_doTransferOut
Performs a transfer out to recipient
function _doTransferOut(address payable to, uint256 amount) internal virtual;
Parameters
| Name | Type | Description |
|---|---|---|
to | address payable | Recipient address |
amount | uint256 | Amount to transfer |
_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 |
_getBlockTimestamp
Retrieves current block timestamp (virtual for tests)
function _getBlockTimestamp() internal view virtual returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current block timestamp |
_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 |
Events
NewRolesOperator
Event emitted when rolesOperator is changed
event NewRolesOperator(address indexed oldRoles, address indexed newRoles);
Parameters
| Name | Type | Description |
|---|---|---|
oldRoles | address | Previous roles contract |
newRoles | address | New roles contract |
NewOperator
Event emitted when Operator is changed
event NewOperator(address indexed oldOperator, address indexed newOperator);
Parameters
| Name | Type | Description |
|---|---|---|
oldOperator | address | Previous operator address |
newOperator | address | New operator address |
NewPendingAdmin
Event emitted when pending admin is updated
event NewPendingAdmin(address indexed pendingAdmin);
Parameters
| Name | Type | Description |
|---|---|---|
pendingAdmin | address | The new pending admin address |
AdminAccepted
Event emitted when admin is accepted
event AdminAccepted(address indexed admin);
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | The new admin address |
Transfer
EIP20 Transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Sender address |
to | address | Receiver address |
amount | uint256 | Amount transferred |
Approval
EIP20 Approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
owner | address | Token owner |
spender | address | Spender address |
amount | uint256 | Allowed amount |
AccrueInterest
Event emitted when interest is accrued
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
Parameters
| Name | Type | Description |
|---|---|---|
cashPrior | uint256 | Cash prior to accrual |
interestAccumulated | uint256 | Interest accumulated during accrual |
borrowIndex | uint256 | New borrow index |
totalBorrows | uint256 | Total borrows after accrual |
Mint
Event emitted when tokens are minted
event Mint(address indexed minter, address indexed receiver, uint256 mintAmount, uint256 mintTokens);
Parameters
| Name | Type | Description |
|---|---|---|
minter | address | Address initiating mint |
receiver | address | Receiver of minted tokens |
mintAmount | uint256 | Amount of underlying supplied |
mintTokens | uint256 | Amount of mTokens minted |
Redeem
Event emitted when tokens are redeemed
event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);
Parameters
| Name | Type | Description |
|---|---|---|
redeemer | address | Address redeeming tokens |
redeemAmount | uint256 | Amount of underlying redeemed |
redeemTokens | uint256 | Number of tokens redeemed |
Borrow
Event emitted when underlying is borrowed
event Borrow(address indexed borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
Parameters
| Name | Type | Description |
|---|---|---|
borrower | address | Borrower address |
borrowAmount | uint256 | Amount borrowed |
accountBorrows | uint256 | Account borrow balance |
totalBorrows | uint256 | Total borrows after action |
RepayBorrow
Event emitted when a borrow is repaid
event RepayBorrow(
address indexed payer,
address indexed borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
Parameters
| Name | Type | Description |
|---|---|---|
payer | address | Address paying back |
borrower | address | Borrower whose debt is reduced |
repayAmount | uint256 | Amount repaid |
accountBorrows | uint256 | Borrower's balance after repay |
totalBorrows | uint256 | Total borrows after repay |
LiquidateBorrow
Event emitted when a borrow is liquidated
event LiquidateBorrow(
address indexed liquidator,
address indexed borrower,
uint256 repayAmount,
address indexed mTokenCollateral,
uint256 seizeTokens
);
Parameters
| Name | Type | Description |
|---|---|---|
liquidator | address | Liquidator address |
borrower | address | Borrower being liquidated |
repayAmount | uint256 | Amount repaid |
mTokenCollateral | address | Collateral market |
seizeTokens | uint256 | Tokens seized |
NewMarketInterestRateModel
Event emitted when interestRateModel is changed
event NewMarketInterestRateModel(address indexed oldInterestRateModel, address indexed newInterestRateModel);
Parameters
| Name | Type | Description |
|---|---|---|
oldInterestRateModel | address | Previous interest rate model |
newInterestRateModel | address | New interest rate model |
NewReserveFactor
Event emitted when the reserve factor is changed
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
Parameters
| Name | Type | Description |
|---|---|---|
oldReserveFactorMantissa | uint256 | Previous reserve factor |
newReserveFactorMantissa | uint256 | New reserve factor |
ReservesAdded
Event emitted when the reserves are added
event ReservesAdded(address indexed benefactor, uint256 addAmount, uint256 newTotalReserves);
Parameters
| Name | Type | Description |
|---|---|---|
benefactor | address | Address adding reserves |
addAmount | uint256 | Amount added |
newTotalReserves | uint256 | Total reserves after addition |
ReservesReduced
Event emitted when the reserves are reduced
event ReservesReduced(address indexed admin, uint256 reduceAmount, uint256 newTotalReserves);
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address removing reserves |
reduceAmount | uint256 | Amount removed |
newTotalReserves | uint256 | Total reserves after reduction |
NewBorrowRateMaxMantissa
Event emitted when the borrow max mantissa is updated
event NewBorrowRateMaxMantissa(uint256 oldVal, uint256 maxMantissa);
Parameters
| Name | Type | Description |
|---|---|---|
oldVal | uint256 | Previous max mantissa |
maxMantissa | uint256 | New max mantissa |
SameChainFlowStateUpdated
Event emitted when same chain flow state is enabled or disabled
event SameChainFlowStateUpdated(address indexed sender, bool _oldState, bool _newState);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | Address updating the state |
_oldState | bool | Previous state |
_newState | bool | New state |
ZkVerifierUpdated
Event emitted when zkVerifier is updated
event ZkVerifierUpdated(address indexed oldVerifier, address indexed newVerifier);
Parameters
| Name | Type | Description |
|---|---|---|
oldVerifier | address | Previous verifier |
newVerifier | address | New verifier |
Errors
mt_OnlyAdmin
Thrown when caller is not admin
error mt_OnlyAdmin();
mt_RedeemEmpty
Thrown when redeem amounts are zero
error mt_RedeemEmpty();
mt_InvalidInput
Thrown when provided input is invalid
error mt_InvalidInput();
mt_OnlyAdminOrRole
Thrown when caller lacks required role
error mt_OnlyAdminOrRole();
mt_PriceFetchFailed
Thrown when price fetch fails
error mt_PriceFetchFailed();
mt_TransferNotValid
Thrown when transfer is not valid
error mt_TransferNotValid();
mt_MinAmountNotValid
Thrown when minimum amount is not met
error mt_MinAmountNotValid();
mt_BorrowRateTooHigh
Thrown when borrow rate exceeds maximum
error mt_BorrowRateTooHigh();
mt_AlreadyInitialized
Thrown when contract is already initialized
error mt_AlreadyInitialized();
mt_ReserveFactorTooHigh
Thrown when reserve factor exceeds limit
error mt_ReserveFactorTooHigh();
mt_ExchangeRateNotValid
Thrown when exchange rate is invalid
error mt_ExchangeRateNotValid();
mt_MarketMethodNotValid
Thrown when market method call is invalid
error mt_MarketMethodNotValid();
mt_LiquidateSeizeTooMuch
Thrown when liquidation seizes too much collateral
error mt_LiquidateSeizeTooMuch();
mt_RedeemCashNotAvailable
Thrown when redeem cash is unavailable
error mt_RedeemCashNotAvailable();
mt_BorrowCashNotAvailable
Thrown when borrow cash is unavailable
error mt_BorrowCashNotAvailable();
mt_ReserveCashNotAvailable
Thrown when reserve cash is unavailable
error mt_ReserveCashNotAvailable();
mt_RedeemTransferOutNotPossible
Thrown when redeem transfer out is not possible
error mt_RedeemTransferOutNotPossible();
mt_SameChainOperationsAreDisabled
Thrown when same chain operations are disabled
error mt_SameChainOperationsAreDisabled();
mt_CollateralBlockTimestampNotValid
Thrown when collateral block timestamp is invalid
error mt_CollateralBlockTimestampNotValid();
mt_AddressNotValid
Thrown when configuration address is invalid
error mt_AddressNotValid();
mt_OperatorNotValid
Thrown when address is not valid
error mt_OperatorNotValid();
mt_NameNotValid
Error thrown when name is not valid
error mt_NameNotValid();
mt_SymbolNotValid
Error thrown when symbol is not valid
error mt_SymbolNotValid();
mt_DecimalsNotValid
Error thrown when decimals are not valid
error mt_DecimalsNotValid();
Structs
BorrowSnapshot
Container for borrow balance information
struct BorrowSnapshot {
/// @notice Total balance (with accrued interest), after applying the most recent balance-changing action
uint256 principal;
/// @notice Global borrowIndex as of the most recent balance-changing action
uint256 interestIndex;
}
Contents
IMendiMarket
Title: IMendiMarket
Author: Merge Layers Inc.
Interface for legacy Mendi market interactions
Functions
repayBorrow
Repays a borrow
function repayBorrow(uint256 repayAmount) external returns (uint256 repaidAmount);
Parameters
| Name | Type | Description |
|---|---|---|
repayAmount | uint256 | Amount to repay or type(uint256).max |
Returns
| Name | Type | Description |
|---|---|---|
repaidAmount | uint256 | Actual repaid amount |
repayBorrowBehalf
Repays a borrow on behalf of borrower
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256 repaidAmount);
Parameters
| Name | Type | Description |
|---|---|---|
borrower | address | Borrower address |
repayAmount | uint256 | Amount to repay |
Returns
| Name | Type | Description |
|---|---|---|
repaidAmount | uint256 | Actual repaid amount |
redeemUnderlying
Redeems underlying for given amount
function redeemUnderlying(uint256 redeemAmount) external returns (uint256 redeemed);
Parameters
| Name | Type | Description |
|---|---|---|
redeemAmount | uint256 | Amount to redeem |
Returns
| Name | Type | Description |
|---|---|---|
redeemed | uint256 | Amount of underlying redeemed |
redeem
Redeems tokens
function redeem(uint256 amount) external returns (uint256 redeemed);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of tokens to redeem |
Returns
| Name | Type | Description |
|---|---|---|
redeemed | uint256 | Amount redeemed |
balanceOfUnderlying
Returns underlying balance of sender
function balanceOfUnderlying(address sender) external returns (uint256 balance);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
balance | uint256 | Underlying balance |
underlying
Returns underlying asset address
function underlying() external view returns (address asset);
Returns
| Name | Type | Description |
|---|---|---|
asset | address | Underlying token |
balanceOf
Returns token balance of sender
function balanceOf(address sender) external view returns (uint256 tokenBalance);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
tokenBalance | uint256 | Token balance |
borrowBalanceStored
Returns stored borrow balance
function borrowBalanceStored(address sender) external view returns (uint256 borrowBalance);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
borrowBalance | uint256 | Borrow balance |
IMendiComptroller
Title: IMendiComptroller
Author: Merge Layers Inc.
Interface for fetching entered markets
Functions
getAssetsIn
Returns assets in for account
function getAssetsIn(address account) external view returns (IMendiMarket[] memory assets);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Account address |
Returns
| Name | Type | Description |
|---|---|---|
assets | IMendiMarket[] | List of markets |
Migrator
Inherits: ExponentialNoError
Title: Migrator
Author: Merge Layers Inc.
Contract for migrating positions from Mendi to Malda
State Variables
MENDI_COMPTROLLER
Mendi Comptroller address
address public constant MENDI_COMPTROLLER = 0x1b4d3b0421dDc1eB216D230Bc01527422Fb93103
MALDA_OPERATOR
Malda Operator address
address public immutable MALDA_OPERATOR
allowedMarkets
Mapping of allowed markets
mapping(address market => bool allowed) public allowedMarkets
Functions
constructor
Initializes the migrator with the operator address
constructor(address _operator) ;
Parameters
| Name | Type | Description |
|---|---|---|
_operator | address | Address of the Malda operator |
getAllPositions
Get all migratable positions from Mendi to Malda for user
function getAllPositions(address user) external returns (Position[] memory positions);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
Returns
| Name | Type | Description |
|---|---|---|
positions | Position[] | Array of positions |
migrateAllPositions
Migrates all positions from Mendi to Malda
function migrateAllPositions() external;
getAllCollateralMarkets
Get all markets where user has collateral in on Mendi
function getAllCollateralMarkets(address user) external view returns (address[] memory markets);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
Returns
| Name | Type | Description |
|---|---|---|
markets | address[] | Array of market addresses |
_mintAll
Mints in v2 markets for all positions with collateral
function _mintAll(Position[] memory positions) private;
Parameters
| Name | Type | Description |
|---|---|---|
positions | Position[] | Positions to process |
_borrowAll
Borrows in v2 markets for all positions requiring debt
function _borrowAll(Position[] memory positions) private;
Parameters
| Name | Type | Description |
|---|---|---|
positions | Position[] | Positions to process |
_repayAll
Repays debts in v1 markets for all positions
function _repayAll(Position[] memory positions) private;
Parameters
| Name | Type | Description |
|---|---|---|
positions | Position[] | Positions to process |
_withdrawAll
Withdraws collateral from v1 and transfers to v2 for all positions
function _withdrawAll(Position[] memory positions) private;
Parameters
| Name | Type | Description |
|---|---|---|
positions | Position[] | Positions to process |
_collectMendiPositions
Collects all user positions from Mendi
function _collectMendiPositions(address user) private returns (Position[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | Position[] | Array of positions |
_getMaldaMarket
Gets corresponding Malda market for a given underlying
function _getMaldaMarket(address underlying) private view returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
underlying | address | The underlying token address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The Malda market address |
Errors
Migrator_AddressNotValid
Error thrown when address is not valid
error Migrator_AddressNotValid();
Migrator_RedeemAmountNotValid
Error thrown when redeem amount is not valid
error Migrator_RedeemAmountNotValid();
Structs
Position
struct Position {
address mendiMarket;
address maldaMarket;
uint256 collateralUnderlyingAmount;
uint256 borrowAmount;
}
Contents
Contents
DefaultGasHelper
Inherits: Ownable
Title: DefaultGasHelper
Author: Merge Layers Inc.
Helper contract for managing gas fees
State Variables
gasFees
Mapping of chain IDs to gas fees
mapping(uint32 chainId => uint256 fee) public gasFees
Functions
constructor
Constructor
constructor(address owner_) Ownable(owner_);
Parameters
| Name | Type | Description |
|---|---|---|
owner_ | address | The owner address |
setGasFee
Sets the gas fee
function setGasFee(uint32 dstChainId, uint256 amount) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | The destination chain id |
amount | uint256 | The gas fee amount |
Events
GasFeeUpdated
Event emitted when gas fee is updated
event GasFeeUpdated(uint32 indexed dstChainId, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint32 | The destination chain ID |
amount | uint256 | The gas fee amount |
ChainlinkOracle
Inherits: IOracleOperator
Title: ChainlinkOracle
Author: Merge Layers Inc.
Oracle contract using Chainlink price feeds
State Variables
DECIMALS
Number of decimals for price
uint8 public constant DECIMALS = 18
priceFeeds
Mapping of symbols to price feeds
mapping(string symbol => IAggregatorV3 feed) public priceFeeds
baseUnits
Mapping of symbols to base units
mapping(string symbol => uint256 units) public baseUnits
Functions
constructor
Constructor
constructor(string[] memory symbols_, IAggregatorV3[] memory feeds_, uint256[] memory baseUnits_) ;
Parameters
| Name | Type | Description |
|---|---|---|
symbols_ | string[] | Array of symbols |
feeds_ | IAggregatorV3[] | Array of price feeds |
baseUnits_ | uint256[] | Array of base units |
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 | price The underlying asset price mantissa (scaled by 1e18). Zero means 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 | price The underlying asset price mantissa (scaled by 1e18). Zero means unavailable. |
_getLatestPrice
Get the latest price for a symbol
function _getLatestPrice(string memory symbol) internal view returns (uint256, uint256);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | The symbol to get price for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | answer The price |
<none> | uint256 | updatedAt The timestamp when the price was last updated |
Errors
ChainlinkOracle_NoPriceFeed
Error thrown when no price feed is found
error ChainlinkOracle_NoPriceFeed();
ChainlinkOracle_ZeroPrice
Error thrown when price is zero
error ChainlinkOracle_ZeroPrice();
MixedPriceOracleV3
Inherits: IOracleOperator
Title: MixedPriceOracleV3
Author: Merge Layers Inc.
Mixed price oracle contract
State Variables
STALENESS_PERIOD
Staleness period
uint256 public immutable STALENESS_PERIOD
ROLES
Roles contract
IRoles public immutable ROLES
configs
Mapping of symbols to price configs
mapping(string symbol => IDefaultAdapter.PriceConfig config) public configs
stalenessPerSymbol
Mapping of symbols to staleness periods
mapping(string symbol => uint256 staleness) public stalenessPerSymbol
Functions
onlyRole
Modifier to check if the caller has specific role
modifier onlyRole(bytes32 role) ;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role identifier to check |
constructor
Initializes the oracle with symbols, configs, roles, and default staleness
constructor(
string[] memory symbols_,
IDefaultAdapter.PriceConfig[] memory configs_,
address roles_,
uint256 stalenessPeriod_
) ;
Parameters
| Name | Type | Description |
|---|---|---|
symbols_ | string[] | Array of token symbols |
configs_ | IDefaultAdapter.PriceConfig[] | Array of price configs for symbols |
roles_ | address | Roles contract address |
stalenessPeriod_ | uint256 | Default staleness period |
setStaleness
Sets a custom staleness period for a symbol
function setStaleness(string calldata symbol, uint256 val) external onlyRole(ROLES.GUARDIAN_ORACLE());
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol to update |
val | uint256 | New staleness value |
setConfig
Sets a price configuration for a symbol
function setConfig(string calldata symbol, IDefaultAdapter.PriceConfig calldata config)
external
onlyRole(ROLES.GUARDIAN_ORACLE());
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol to configure |
config | IDefaultAdapter.PriceConfig | Price configuration |
getUnderlyingPrice
Returns underlying price for an mToken
function getUnderlyingPrice(address mToken) external view override returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Address of the mToken |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Price denominated in USD with 18 decimals adjusted for underlying decimals |
getPrice
Returns price for an mToken
function getPrice(address mToken) public view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Address of the mToken |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Price denominated in USD with 18 decimals |
_getPriceUSD
Returns the USD price for a symbol
function _getPriceUSD(string memory symbol) internal view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | price Price denominated in USD with 18 decimals |
_getLatestPrice
Fetches the latest price from configured feeds
function _getLatestPrice(string memory symbol, IDefaultAdapter.PriceConfig memory config)
internal
view
returns (uint256, uint256);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
config | IDefaultAdapter.PriceConfig | Price configuration for the symbol |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | price Latest price from feed |
<none> | uint256 | decimals Decimals returned by the feed |
_getStaleness
Returns staleness for a symbol or default if not set
function _getStaleness(string memory symbol) internal view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Staleness period in seconds |
_onlyRole
Ensures caller has specific role
function _onlyRole(bytes32 role) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role identifier to check |
Events
ConfigSet
Emitted when a configuration is set for a symbol
event ConfigSet(string symbol, IDefaultAdapter.PriceConfig config);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol being configured |
config | IDefaultAdapter.PriceConfig | Price configuration applied |
StalenessUpdated
Emitted when staleness is updated for a symbol
event StalenessUpdated(string symbol, uint256 val);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol being updated |
val | uint256 | New staleness value |
Errors
MixedPriceOracle_Unauthorized
Error thrown when caller lacks required role
error MixedPriceOracle_Unauthorized();
MixedPriceOracle_StalePrice
Error thrown when price is stale
error MixedPriceOracle_StalePrice();
MixedPriceOracle_InvalidPrice
Error thrown when price returned is invalid
error MixedPriceOracle_InvalidPrice();
MixedPriceOracle_InvalidRound
Error thrown when price round is invalid
error MixedPriceOracle_InvalidRound();
MixedPriceOracle_InvalidConfig
Error thrown when configuration is invalid
error MixedPriceOracle_InvalidConfig();
MixedPriceOracle_AddressNotValid
Error thrown when roles contract address is invalid
error MixedPriceOracle_AddressNotValid();
MixedPriceOracleV4
Inherits: IOracleOperator
Title: MixedPriceOracleV4
Author: Merge Layers Inc.
Mixed price oracle using dual feeds and staleness checks
State Variables
PRICE_DELTA_EXP
Price delta exponent (basis points denominator)
uint256 public constant PRICE_DELTA_EXP = 1e5
STALENESS_PERIOD
Default staleness period applied to feeds
uint256 public immutable STALENESS_PERIOD
ROLES
Roles contract reference
IRoles public immutable ROLES
configs
Mapping of symbols to price configs
mapping(string symbol => PriceConfig config) public configs
stalenessPerSymbol
Mapping of symbols to custom staleness
mapping(string symbol => uint256 staleness) public stalenessPerSymbol
deltaPerSymbol
Mapping of symbols to custom price deltas
mapping(string symbol => uint256 delta) public deltaPerSymbol
maxPriceDelta
Maximum allowed delta in basis points for price comparison
uint256 public maxPriceDelta = 1.5e3
Functions
onlyRole
Modifier to check if the caller has specific role
modifier onlyRole(bytes32 role) ;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role identifier to check |
constructor
Initializes the oracle with configs, roles, and staleness
constructor(string[] memory symbols_, PriceConfig[] memory configs_, address roles_, uint256 stalenessPeriod_) ;
Parameters
| Name | Type | Description |
|---|---|---|
symbols_ | string[] | Symbols being configured |
configs_ | PriceConfig[] | Price configs for symbols |
roles_ | address | Roles contract address |
stalenessPeriod_ | uint256 | Default staleness period |
setStaleness
Sets a custom staleness for a symbol
function setStaleness(string calldata symbol, uint256 val) external onlyRole(ROLES.GUARDIAN_ORACLE());
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol to update |
val | uint256 | New staleness value |
setConfig
Sets price configuration for a symbol
function setConfig(string calldata symbol, PriceConfig calldata config) external onlyRole(ROLES.GUARDIAN_ORACLE());
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol to configure |
config | PriceConfig | Price configuration |
setMaxPriceDelta
Sets maximum allowed price delta
function setMaxPriceDelta(uint256 _delta) external onlyRole(ROLES.GUARDIAN_ORACLE());
Parameters
| Name | Type | Description |
|---|---|---|
_delta | uint256 | New max delta in basis points |
setSymbolMaxPriceDelta
Sets maximum price delta for a specific symbol
function setSymbolMaxPriceDelta(uint256 _delta, string calldata _symbol)
external
onlyRole(ROLES.GUARDIAN_ORACLE());
Parameters
| Name | Type | Description |
|---|---|---|
_delta | uint256 | New delta in basis points |
_symbol | string | Symbol to update |
getPrice
Returns price for an mToken
function getPrice(address mToken) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Address of the mToken |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Price denominated in USD with 18 decimals |
getUnderlyingPrice
Returns underlying price for an mToken
function getUnderlyingPrice(address mToken) external view override returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Address of the mToken |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Price denominated in USD with 18 decimals adjusted for underlying decimals |
_onlyRole
Ensures caller has specific role
function _onlyRole(bytes32 role) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role identifier to check |
_getPriceUSD
Returns USD price for a symbol using dual feeds
function _getPriceUSD(string memory symbol) internal view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | USD price with 18 decimals |
_getApi3Price
Retrieves price and last update from API3 feed
function _getApi3Price(string memory symbol) internal view returns (uint256 price, uint256 lastUpdate);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | Price scaled to 18 decimals |
lastUpdate | uint256 | Timestamp of last update |
_geteOraclePrice
Retrieves price and last update from eOracle feed
function _geteOraclePrice(string memory symbol) internal view returns (uint256 price, uint256 lastUpdate);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | Price scaled to 18 decimals |
lastUpdate | uint256 | Timestamp of last update |
_isFresh
Checks if price data is fresh
function _isFresh(uint256 updatedAt, uint256 staleness) internal view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
updatedAt | uint256 | Timestamp of last update |
staleness | uint256 | Allowed staleness threshold |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if data is within staleness window |
_getStaleness
Returns staleness for a symbol or default
function _getStaleness(string memory symbol) internal view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Token symbol |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Staleness period in seconds |
_absDiff
Absolute difference between two int256 values
function _absDiff(int256 a, int256 b) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
a | int256 | First value |
b | int256 | Second value |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Absolute difference as uint256 |
Events
ConfigSet
Emitted when a config is set for a symbol
event ConfigSet(string symbol, PriceConfig config);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol being configured |
config | PriceConfig | Price config stored |
StalenessUpdated
Emitted when staleness is updated for a symbol
event StalenessUpdated(string symbol, uint256 val);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | Symbol being updated |
val | uint256 | New staleness period |
PriceDeltaUpdated
Emitted when global price delta is updated
event PriceDeltaUpdated(uint256 oldVal, uint256 newVal);
Parameters
| Name | Type | Description |
|---|---|---|
oldVal | uint256 | Previous delta value |
newVal | uint256 | New delta value |
PriceSymbolDeltaUpdated
Emitted when symbol price delta is updated
event PriceSymbolDeltaUpdated(uint256 oldVal, uint256 newVal, string symbol);
Parameters
| Name | Type | Description |
|---|---|---|
oldVal | uint256 | Previous delta |
newVal | uint256 | New delta |
symbol | string | Symbol affected |
Errors
MixedPriceOracle_Unauthorized
Error thrown when caller is unauthorized
error MixedPriceOracle_Unauthorized();
MixedPriceOracle_ApiV3StalePrice
Error thrown when API3 feed price is stale
error MixedPriceOracle_ApiV3StalePrice();
MixedPriceOracle_eOracleStalePrice
Error thrown when eOracle feed price is stale
error MixedPriceOracle_eOracleStalePrice();
MixedPriceOracle_InvalidPrice
Error thrown when price returned is invalid
error MixedPriceOracle_InvalidPrice();
MixedPriceOracle_InvalidConfig
Error thrown when provided config is invalid
error MixedPriceOracle_InvalidConfig();
MixedPriceOracle_DeltaTooHigh
Error thrown when delta exceeds allowed max
error MixedPriceOracle_DeltaTooHigh();
MixedPriceOracle_MissingFeed
Error thrown when required feed is missing
error MixedPriceOracle_MissingFeed();
MixedPriceOracle_AddressNotValid
Error thrown when roles contract address is invalid
error MixedPriceOracle_AddressNotValid();
Structs
PriceConfig
struct PriceConfig {
address api3Feed;
address eOracleFeed;
string toSymbol;
uint256 underlyingDecimals;
}
Contents
Pauser
Inherits: Ownable, IPauser
Title: Pauser
Author: Merge Layers Inc.
Manages pausing operations across deployed markets
State Variables
ROLES
Roles contract reference
IRoles public immutable ROLES
OPERATOR
Operator contract reference
IOperator public immutable OPERATOR
pausableContracts
List of contracts that can be paused
PausableContract[] public pausableContracts
registeredContracts
Tracks whether a contract is registered as pausable
mapping(address _contract => bool _registered) public registeredContracts
contractTypes
Contract type for each registered market
mapping(address _contract => PausableType _type) public contractTypes
Functions
constructor
Sets initial configuration for roles, operator, and owner
constructor(address _roles, address _operator, address owner_) Ownable(owner_);
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | Address of the roles contract |
_operator | address | Address of the operator contract |
owner_ | address | Owner address of the pauser contract |
addPausableMarket
Add pausable 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 pausable 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
function emergencyPauseMarketFor(address _market, ImTokenOperationTypes.OperationType _pauseType) external;
emergencyPauseAll
Pauses all operations for all registered markets
function emergencyPauseAll() external;
_pauseAllMarketOperations
Pauses all market operations for a given market
function _pauseAllMarketOperations(address _market) private;
Parameters
| Name | Type | Description |
|---|---|---|
_market | address | The market to pause |
_pauseMarketOperation
Pauses a specific market operation type
function _pauseMarketOperation(address _market, ImTokenOperationTypes.OperationType _pauseType) private;
Parameters
| Name | Type | Description |
|---|---|---|
_market | address | The market to pause |
_pauseType | ImTokenOperationTypes.OperationType | The operation type to pause |
_pause
Performs pause logic depending on contract type
function _pause(address _market, ImTokenOperationTypes.OperationType _pauseType) private;
Parameters
| Name | Type | Description |
|---|---|---|
_market | address | The market address to pause |
_pauseType | ImTokenOperationTypes.OperationType | The operation type to pause |
_findIndex
Finds the index of a market within the pausableContracts array
function _findIndex(address _address) private view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
_address | address | The market address to search for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | index The index of the market |
Contents
Contents
AccrossBridge
Inherits: BaseBridge, IBridge, IAcrossReceiverV3, ReentrancyGuard
Title: AcrossBridge
Author: Merge Layers Inc.
Bridge integration for Across V3 used by the rebalancer
State Variables
SLIPPAGE_PRECISION
Precision used for slippage calculations
uint256 private constant SLIPPAGE_PRECISION = 1e5
ACROSS_SPOKE_POOL
Across spoke pool address
address public immutable ACROSS_SPOKE_POOL
MAX_SLIPPAGE
Maximum allowed slippage in basis points
uint256 public immutable MAX_SLIPPAGE
REBALANCER
Rebalancer contract address
address public immutable REBALANCER
whitelistedRelayers
Whitelisted relayers per destination chain
mapping(uint32 dstChainId => mapping(address relayer => bool isWhitelisted)) public whitelistedRelayers
Functions
onlySpokePool
Modifier to restrict access to only the spoke pool
modifier onlySpokePool() ;
constructor
Initializes the Across bridge
constructor(address _roles, address _spokePool, address _rebalancer) BaseBridge(_roles);
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | Address of the roles contract |
_spokePool | address | Address of the Across spoke pool |
_rebalancer | address | Address of the rebalancer contract |
setWhitelistedRelayer
Whitelists or removes a relayer for a destination chain
function setWhitelistedRelayer(uint32 _dstId, address _relayer, bool status) external onlyBridgeConfigurator;
Parameters
| Name | Type | Description |
|---|---|---|
_dstId | uint32 | The destination chain ID |
_relayer | address | The relayer address to update |
status | bool | Whether the relayer is whitelisted |
handleV3AcrossMessage
handles AcrossV3 SpokePool message
function handleV3AcrossMessage(
address tokenSent,
uint256 amount,
address, /* relayer is unused */
bytes calldata 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 |
sendMsg
rebalance through bridge
function sendMsg(
uint256 _extractedAmount,
address _market,
uint32 _dstChainId,
address _token,
bytes calldata _message,
bytes calldata /* _bridgeData */
) 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 |
isRelayerWhitelisted
Returns whether an address is whitelisted as relayer for a destination chain
function isRelayerWhitelisted(uint32 dstChain, address relayer) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
dstChain | uint32 | The destination chain ID |
relayer | address | The relayer address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isWhitelisted True if relayer is whitelisted |
getFee
computes fee for bridge operation
function getFee(
uint32,
/* _dstChainId */
bytes calldata,
/* _message */
bytes calldata /* _bridgeData */
)
external
pure
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | uint32 | |
<none> | bytes | |
<none> | bytes |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | fee Computed bridge fee |
_depositV3Now
Deposits funds into Across spoke pool for immediate relay
function _depositV3Now(bytes calldata _message, address _token, uint32 _dstChainId, address _market) private;
Parameters
| Name | Type | Description |
|---|---|---|
_message | bytes | Encoded Across message |
_token | address | Token being transferred |
_dstChainId | uint32 | Destination chain ID |
_market | address | Market address encoded in the message |
_decodeMessage
Decodes the Across message payload
function _decodeMessage(bytes calldata _message) private pure returns (DecodedMessage memory messageData);
Parameters
| Name | Type | Description |
|---|---|---|
_message | bytes | Encoded message data |
Returns
| Name | Type | Description |
|---|---|---|
messageData | DecodedMessage | The decoded message struct |
Events
Rebalanced
Emitted when funds are rebalanced to a market
event Rebalanced(address indexed market, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | The market receiving funds |
amount | uint256 | The amount rebalanced |
WhitelistedRelayerStatusUpdated
Emitted when relayer whitelist status is updated
event WhitelistedRelayerStatusUpdated(
address indexed sender, uint32 indexed dstId, address indexed delegate, bool status
);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The caller updating whitelist |
dstId | uint32 | The destination chain ID |
delegate | address | The relayer address |
status | bool | The whitelist status |
Errors
AcrossBridge_TokenMismatch
Error thrown when tokens do not match expected underlying
error AcrossBridge_TokenMismatch();
AcrossBridge_NotAuthorized
Error thrown when caller is not authorized
error AcrossBridge_NotAuthorized();
AcrossBridge_NotImplemented
Error thrown when feature is not implemented
error AcrossBridge_NotImplemented();
AcrossBridge_AddressNotValid
Error thrown when an address is not valid
error AcrossBridge_AddressNotValid();
AcrossBridge_SlippageNotValid
Error thrown when slippage exceeds maximum
error AcrossBridge_SlippageNotValid();
AcrossBridge_RelayerNotValid
Error thrown when relayer is not valid
error AcrossBridge_RelayerNotValid();
AcrossBridge_InvalidReceiver
Error thrown when receiver market is invalid
error AcrossBridge_InvalidReceiver();
AcrossBridge_MaxFeeExceeded
Error thrown when relayer fee exceeds maximum
error AcrossBridge_MaxFeeExceeded();
Structs
DecodedMessage
Decoded Across message payload
struct DecodedMessage {
address outputToken;
uint256 inputAmount;
uint256 outputAmount;
address relayer;
uint32 deadline;
uint32 exclusivityDeadline;
}
BaseBridge
Title: Base bridge contract
Author: Malda Protocol
Abstract base for cross-chain bridge implementations with role-based access control
State Variables
roles
Roles contract for access control
IRoles public roles
Functions
onlyBridgeConfigurator
Modifier to check if the caller is the bridge configurator
modifier onlyBridgeConfigurator() ;
onlyRebalancer
Modifier to check if the caller is the rebalancer
modifier onlyRebalancer() ;
constructor
Initializes the base bridge
constructor(address _roles) ;
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | Roles contract address |
Errors
BaseBridge_NotAuthorized
Error thrown when caller is not authorized
error BaseBridge_NotAuthorized();
BaseBridge_AmountMismatch
Error thrown when amount mismatch
error BaseBridge_AmountMismatch();
BaseBridge_AmountNotValid
Error thrown when amount is not valid
error BaseBridge_AmountNotValid();
BaseBridge_AddressNotValid
Error thrown when address is not valid
error BaseBridge_AddressNotValid();
EverclearBridge
Inherits: BaseBridge, IBridge
Title: Everclear bridge implementation
Author: Malda Protocol
Cross-chain bridge using Everclear protocol for intent-based transfers
State Variables
everclearFeeAdapter
Everclear fee adapter contract
IFeeAdapter public everclearFeeAdapter
Functions
constructor
Initializes the Everclear bridge
constructor(address _roles, address _feeAdapter) BaseBridge(_roles);
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | Roles contract address |
_feeAdapter | address | Everclear fee adapter address |
sendMsg
rebalance through bridge
function sendMsg(
uint256 _extractedAmount,
address _market,
uint32 _dstChainId,
address _token,
bytes calldata _message,
bytes calldata /* _bridgeData */
) 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 |
getFee
computes fee for bridge operation
function getFee(uint32, bytes calldata, bytes calldata) external pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | uint32 | |
<none> | bytes | |
<none> | bytes |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | fee Computed bridge fee |
_decodeIntent
Decodes an intent message returned by the Everclear intents API into structured parameters.
- The input
messageis the raw ABI-encoded calldata of aFeeAdapter.newIntentcall. - The first 4 bytes are the function selector, which are skipped.
- The remaining bytes encode the primary intent parameters followed by
FeeParams. - Because
FeeParamsis a dynamic struct appended at the end, its data must be located by reading its offset and decoding separately. Layout ofFeeAdapter.newIntentcalldata after the selector:
destinations (uint32[]) at offset 0x00
receiver (bytes32) at offset 0x20
inputAsset (address) at offset 0x40
outputAsset (bytes32) at offset 0x60
amount (uint256) at offset 0x80
maxFee (uint24) at offset 0xa0
ttl (uint48) at offset 0xc0
data (bytes) at offset 0xe0
feeParams (FeeParams) at offset 0x100 (9th arg → pointer)
Since each static argument occupies a 32-byte slot, the pointer to feeParams
lives at offset 0x100 (256 bytes) after the selector is removed.
function _decodeIntent(bytes memory message) internal pure returns (IntentParams memory);
Parameters
| Name | Type | Description |
|---|---|---|
message | bytes | ABI-encoded calldata for FeeAdapter.newIntent. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | IntentParams | Decoded IntentParams struct with both core parameters and nested FeeParams. |
_extractFeeParams
Extracts the nested FeeParams struct from ABI-encoded intentData.
FeeParamsis the 9th parameter ofFeeAdapter.newIntentand therefore stored as a pointer at offset0x100.- The selector has already been removed, so the pointer is read at byte position
0x100(256 bytes). - The pointer gives the offset to the start of the
FeeParamsstruct relative to the start of intentData. - Within
FeeParams, the layout is:
fee (uint256) at +0x00
deadline (uint256) at +0x20
sig (bytes) at +0x40 (stored as offset → length → data)
- The
sigfield is dynamic, so we read its offset (at +0x40) relative to theFeeParamsbase, then read the length at that offset, then slice out the actual signature bytes.
function _extractFeeParams(bytes memory intentData)
private
pure
returns (uint256 fee, uint256 deadline, bytes memory sig);
Parameters
| Name | Type | Description |
|---|---|---|
intentData | bytes | ABI-encoded calldata without selector, containing intent arguments. |
Returns
| Name | Type | Description |
|---|---|---|
fee | uint256 | The fee value. |
deadline | uint256 | The signature deadline. |
sig | bytes | The validator/relayer signature. |
Events
MsgSent
Emitted when a message is sent via Everclear
event MsgSent(uint256 indexed dstChainId, address indexed market, uint256 amountLD, bytes32 id);
Parameters
| Name | Type | Description |
|---|---|---|
dstChainId | uint256 | Destination chain ID |
market | address | Market address |
amountLD | uint256 | Amount in local decimals |
id | bytes32 | Intent identifier |
RebalancingReturnedToMarket
Emitted when excess rebalancing funds are returned to the market
event RebalancingReturnedToMarket(address indexed market, uint256 toReturn, uint256 extracted);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | Market address |
toReturn | uint256 | Amount returned |
extracted | uint256 | Amount originally extracted |
Errors
Everclear_TokenMismatch
Error thrown when provided token does not match expected asset
error Everclear_TokenMismatch();
Everclear_NotImplemented
Error thrown when a feature is not implemented
error Everclear_NotImplemented();
Everclear_MaxFeeExceeded
Error thrown when maximum fee is exceeded
error Everclear_MaxFeeExceeded();
Everclear_AddressNotValid
Error thrown when provided address is invalid
error Everclear_AddressNotValid();
Everclear_DestinationNotValid
Error thrown when provided destination is invalid
error Everclear_DestinationNotValid();
Everclear_DestinationsLengthMismatch
Error thrown when destination arrays have mismatched length
error Everclear_DestinationsLengthMismatch();
Structs
IntentParams
struct IntentParams {
uint32[] destinations;
bytes32 receiver;
address inputAsset;
bytes32 outputAsset;
uint256 amount;
uint24 maxFee;
uint48 ttl;
bytes data;
IFeeAdapter.FeeParams feeParams;
}
Rebalancer
Inherits: IRebalancer, HypernativeFirewallProtected, ReentrancyGuard
Title: Cross-chain rebalancer
Author: Malda Protocol
Manages bridge interactions and transfer size limits for cross-chain rebalancing.
State Variables
roles
Roles contract used for access control
IRoles public roles
nonce
Incremental nonce used for logging messages
uint256 public nonce
logs
Sent messages indexed by destination chain and nonce
mapping(uint32 chainId => mapping(uint256 nonce => Msg message)) public logs
whitelistedBridges
Bridge whitelist status
mapping(address bridge => bool whitelisted) public whitelistedBridges
allowedTokensPerBridge
Allowed tokens per bridge
mapping(address bridge => mapping(address token => bool allowed)) public allowedTokensPerBridge
whitelistedDestinations
Destination chain whitelist status
mapping(uint32 dstChainId => bool whitelisted) public whitelistedDestinations
allowedList
Markets allowed for rebalancing
mapping(address market => bool allowed) public allowedList
admin
Admin address with elevated permissions
address public admin
saveAddress
Address used to sweep saved assets
address public saveAddress
maxTransferSizes
Per-chain token maximum transfer size
mapping(uint32 dstChainId => mapping(address token => uint256 maxSize)) public maxTransferSizes
minTransferSizes
Per-chain token minimum transfer size
mapping(uint32 dstChainId => mapping(address token => uint256 minSize)) public minTransferSizes
currentTransferSize
Rolling transfer info for size-window enforcement
mapping(uint32 dstChainId => mapping(address token => TransferInfo transferInfo)) public currentTransferSize
whitelistedMarkets
Market whitelist status
mapping(address market => bool whitelisted) public whitelistedMarkets
transferTimeWindow
Duration of the rolling transfer size window
uint256 public transferTimeWindow
Functions
constructor
Initializes the Rebalancer
constructor(address _roles, address _saveAddress, address _admin) ;
Parameters
| Name | Type | Description |
|---|---|---|
_roles | address | Roles contract |
_saveAddress | address | Address to sweep saved assets to |
_admin | address | Admin address |
setAllowedTokens
Set allowed tokens for a bridge
function setAllowedTokens(address bridge, address[] calldata tokens, bool status) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
bridge | address | Bridge address |
tokens | address[] | Token list to allow/disallow |
status | bool | Allowance status |
setMarketStatus
Batch whitelist/unwhitelist markets
function setMarketStatus(address[] calldata list, bool status) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
list | address[] | Market addresses |
status | bool | Whitelist status |
setAllowList
Batch set allow-list status for markets
function setAllowList(address[] calldata list, bool status) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
list | address[] | Market addresses |
status | bool | Allow list status |
setWhitelistedBridgeStatus
Set whitelist status for a bridge
function setWhitelistedBridgeStatus(address _bridge, bool status_) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
_bridge | address | Bridge address |
status_ | bool | Whitelist status |
setWhitelistedDestination
Set whitelist status for a destination chain
function setWhitelistedDestination(uint32 _dstId, bool status_) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
_dstId | uint32 | Destination chain id |
status_ | bool | Whitelist status |
saveEth
Sweep native ETH to the configured save address
function saveEth() external onlyFirewallApproved;
saveTokens
Sweep stray tokens to the given market
function saveTokens(address token, address market) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to sweep |
market | address | Market to receive tokens |
setMinTransferSize
Set minimum transfer size for a destination/token
function setMinTransferSize(uint32 _dstChainId, address _token, uint256 _limit) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
_dstChainId | uint32 | Destination chain id |
_token | address | Token address |
_limit | uint256 | Minimum size |
setMaxTransferSize
Set maximum transfer size for a destination/token
function setMaxTransferSize(uint32 _dstChainId, address _token, uint256 _limit) external onlyFirewallApproved;
Parameters
| Name | Type | Description |
|---|---|---|
_dstChainId | uint32 | Destination chain id |
_token | address | Token address |
_limit | uint256 | Maximum size |
sendMsg
Sends a bridge message
function sendMsg(address _bridge, address _market, uint256 _amount, Msg calldata _msg)
external
payable
onlyFirewallApproved
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
_bridge | address | |
_market | address | The market to rebalance from address |
_amount | uint256 | The amount to rebalance |
_msg | Msg | The message data |
isMarketWhitelisted
Returns if a market is whitelisted
function isMarketWhitelisted(address market) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
market | address | Market address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | whitelisted True if whitelisted |
isBridgeWhitelisted
Returns if a bridge implementation is whitelisted
function isBridgeWhitelisted(address bridge) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
bridge | address | Bridge address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | whitelisted True if whitelisted |
isDestinationWhitelisted
Returns if a destination is whitelisted
function isDestinationWhitelisted(uint32 dstId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
dstId | uint32 | Destination chain ID |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | whitelisted True if whitelisted |
firewallRegister
Registers an account with the firewall
function firewallRegister(address _account) public override(HypernativeFirewallProtected);
Parameters
| Name | Type | Description |
|---|---|---|
_account | address | Account to register |
Structs
TransferInfo
struct TransferInfo {
uint256 size;
uint256 timestamp;
}
Contents
ReferralSigning
Title: Referral signing contract
Author: Malda Protocol
Manages user referrals with signature-based verification
State Variables
referredByRegistry
Tracks if a user was referred by a specific referrer
mapping(address referredBy => mapping(address user => bool wasReferred)) public referredByRegistry
referralsForUserRegistry
Maps users to their referrer
mapping(address user => address referredBy) public referralsForUserRegistry
referralRegistry
Lists all users referred by a referrer
mapping(address referredBy => address[] users) public referralRegistry
totalReferred
Total number of users referred by a referrer
mapping(address referredBy => uint256 total) public totalReferred
isUserReferred
Tracks if a user has been referred
mapping(address user => bool wasReferred) public isUserReferred
nonces
Nonce for each user to prevent replay attacks
mapping(address user => uint256 nonce) public nonces
Functions
onlyNewUser
Modifier to check if the user is a new user
modifier onlyNewUser() ;
claimReferral
Claims a referral with signature verification
function claimReferral(bytes calldata signature, address referrer) external onlyNewUser;
Parameters
| Name | Type | Description |
|---|---|---|
signature | bytes | User's signature proving consent |
referrer | address | Address of the referrer |
Events
ReferralClaimed
Emitted when a referral is successfully claimed
event ReferralClaimed(address indexed referred, address indexed referrer);
Parameters
| Name | Type | Description |
|---|---|---|
referred | address | The referred user |
referrer | address | The referrer |
ReferralRejected
Emitted when a referral claim is rejected
event ReferralRejected(address indexed referred, address indexed referrer, string reason);
Parameters
| Name | Type | Description |
|---|---|---|
referred | address | The referred user |
referrer | address | The referrer |
reason | string | Rejection reason |
Errors
ReferralSigning_SameUser
Error thrown when the user is the same as the referrer
error ReferralSigning_SameUser();
ReferralSigning_InvalidSignature
Error thrown when the signature is invalid
error ReferralSigning_InvalidSignature();
ReferralSigning_UserAlreadyReferred
Error thrown when the user has already been referred
error ReferralSigning_UserAlreadyReferred();
ReferralSigning_ContractReferrerNotAllowed
Error thrown when the referrer is a contract
error ReferralSigning_ContractReferrerNotAllowed();
Contents
RewardDistributor
Inherits: IRewardDistributor, ExponentialNoError, Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable
Title: Reward distribution manager
Author: Malda Protocol
Distributes reward tokens to suppliers and borrowers across markets.
State Variables
REWARD_INITIAL_INDEX
Initial index used when starting accruals
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 rewardToken => mapping(address mToken => IRewardDistributorData.RewardMarketState marketState))
public rewardMarketState
rewardAccountState
The Reward state for each reward token for each account
mapping(
address rewardToken => mapping(address account => IRewardDistributorData.RewardAccountState accountState)
) public rewardAccountState
rewardTokens
Added reward tokens
address[] public rewardTokens
isRewardToken
mapping(address rewardToken => bool status) public isRewardToken
Functions
onlyOperator
Modifier to check if the caller is the operator
modifier onlyOperator() ;
constructor
Disable initializers for the implementation
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
setOperator
Sets the operator allowed to notify indices
function setOperator(address _operator) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
_operator | address | Operator address |
notifySupplyIndex
Updates supply indices for all reward tokens on a market
function notifySupplyIndex(address mToken) external override onlyOperator;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market token |
notifyBorrowIndex
Updates borrow indices for all reward tokens on a market
function notifyBorrowIndex(address mToken) external override onlyOperator;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market token |
notifySupplier
Accrues supplier rewards for all reward tokens on a market
function notifySupplier(address mToken, address supplier) external override onlyOperator;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market address |
supplier | address | Supplier address |
notifyBorrower
Accrues borrower rewards for all reward tokens on a market
function notifyBorrower(address mToken, address borrower) external override onlyOperator;
Parameters
| Name | Type | Description |
|---|---|---|
mToken | address | Market address |
borrower | address | Borrower address |
initialize
Initializes the upgradeable contract
function initialize(address _owner) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
_owner | address | Owner address |
claim
Claims rewards for a list of holders across all reward tokens
function claim(address[] memory holders) public override nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
holders | address[] | Account list to claim for |
whitelistToken
Whitelists a new reward token
function whitelistToken(address rewardToken_) public onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken_ | address | Reward token address |
updateRewardSpeeds
Updates reward speeds for multiple markets
function updateRewardSpeeds(
address rewardToken_,
address[] memory mTokens,
uint256[] memory supplySpeeds,
uint256[] memory borrowSpeeds
) public onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken_ | address | Reward token address |
mTokens | address[] | Market addresses |
supplySpeeds | uint256[] | Supply speeds per market |
borrowSpeeds | uint256[] | Borrow speeds per market |
getBlockTimestamp
Get block timestamp
function getBlockTimestamp() public view override returns (uint32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint32 | timestamp Current block timestamp |
getRewardTokens
Added reward tokens
function getRewardTokens() public view override returns (address[] memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address[] | rewardTokens Array of reward token addresses |
_claim
Claims rewards for holders for a given token
function _claim(address rewardToken, address[] memory holders) internal;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
holders | address[] | Holder list |
_grantReward
Transfers accrued rewards to a user
function _grantReward(address token, address user, uint256 amount) internal returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Reward token |
user | address | Recipient address |
amount | uint256 | Amount to grant |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Remaining amount (if transfer not fully executed) |
_updateRewardSpeed
Updates supply/borrow speed and indexes for a market
function _updateRewardSpeed(address rewardToken, address mToken, uint256 supplySpeed, uint256 borrowSpeed) private;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market address |
supplySpeed | uint256 | New supply speed |
borrowSpeed | uint256 | New borrow speed |
_notifySupplyIndex
Updates supply index for a reward token/market pair
function _notifySupplyIndex(address rewardToken, address mToken) private;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market address |
_notifyBorrowIndex
Updates borrow index for a reward token/market pair
function _notifyBorrowIndex(address rewardToken, address mToken) private;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market address |
_notifySupplier
Accrues supplier rewards for a market
function _notifySupplier(address rewardToken, address mToken, address supplier) private;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market address |
supplier | address | Supplier address |
_notifyBorrower
Accrues borrower rewards for a market
function _notifyBorrower(address rewardToken, address mToken, address borrower) private;
Parameters
| Name | Type | Description |
|---|---|---|
rewardToken | address | Reward token address |
mToken | address | Market address |
borrower | address | Borrower address |
Errors
RewardDistributor_OnlyOperator
Error thrown when the caller is not the operator
error RewardDistributor_OnlyOperator();
RewardDistributor_TransferFailed
Error thrown when the transfer fails
error RewardDistributor_TransferFailed();
RewardDistributor_RewardNotValid
Error thrown when the reward token is not valid
error RewardDistributor_RewardNotValid();
RewardDistributor_AddressNotValid
Error thrown when the address is not valid
error RewardDistributor_AddressNotValid();
RewardDistributor_AddressAlreadyRegistered
Error thrown when the address is already registered
error RewardDistributor_AddressAlreadyRegistered();
RewardDistributor_SupplySpeedArrayLengthMismatch
Error thrown when the supply speed array length mismatch
error RewardDistributor_SupplySpeedArrayLengthMismatch();
RewardDistributor_BorrowSpeedArrayLengthMismatch
Error thrown when the borrow speed array length mismatch
error RewardDistributor_BorrowSpeedArrayLengthMismatch();
Contents
Deployer
Title: CREATE3-based deployer with admin control
Author: Malda Protocol
Minimal helper to precompute and deploy contracts via CREATE3 with two-step admin handover.
State Variables
admin
Current admin authorized to deploy and manage ownership
address public admin
pendingAdmin
Pending admin address that can accept control
address public pendingAdmin
Functions
onlyAdmin
Modifier to check if the caller is the admin
modifier onlyAdmin() ;
constructor
Initializes the deployer
constructor(address _admin) ;
Parameters
| Name | Type | Description |
|---|---|---|
_admin | address | Address that will control deployments |
receive
Accepts plain ETH transfers
receive() external payable;
setPendingAdmin
Propose a new admin that must later accept
function setPendingAdmin(address newAdmin) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
newAdmin | address | Address proposed as the next admin |
saveEth
Withdraws all ETH to the admin
function saveEth() external onlyAdmin;
setNewAdmin
Directly sets a new admin (without pending/accept)
function setNewAdmin(address _addr) external onlyAdmin;
Parameters
| Name | Type | Description |
|---|---|---|
_addr | address | New admin address |
create
Deploys a contract using CREATE3
function create(bytes32 salt, bytes calldata code) external payable onlyAdmin returns (address deployed);
Parameters
| Name | Type | Description |
|---|---|---|
salt | bytes32 | Deterministic salt used for CREATE3 |
code | bytes | Creation bytecode to deploy |
Returns
| Name | Type | Description |
|---|---|---|
deployed | address | The deployed contract address |
acceptAdmin
Allows the pending admin to accept control
function acceptAdmin() external;
precompute
Precomputes the deployment address for a given salt
function precompute(bytes32 salt) external view returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
salt | bytes32 | Deterministic salt used for CREATE3 |
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The address that would be deployed |
Events
AdminSet
Emitted when admin is updated
event AdminSet(address indexed _admin);
Parameters
| Name | Type | Description |
|---|---|---|
_admin | address | New admin address |
PendingAdminSet
Emitted when pending admin is set
event PendingAdminSet(address indexed _admin);
Parameters
| Name | Type | Description |
|---|---|---|
_admin | address | Pending admin address |
AdminAccepted
Emitted when pending admin accepts control
event AdminAccepted(address indexed _admin);
Parameters
| Name | Type | Description |
|---|---|---|
_admin | address | The admin address that just accepted |
Errors
NotAuthorized
Error thrown when the caller is not the admin
error NotAuthorized(address admin, address sender);
ExponentialNoError
Title: Exponential module for storing fixed-precision decimals
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
EXP_SCALE
Scale factor for exponential calculations
uint256 internal constant EXP_SCALE = 1e18
DOUBLE_SCALE
Scale factor for double precision calculations
uint256 internal constant DOUBLE_SCALE = 1e36
HALF_EXP_SCALE
Half of the scale factor for exponential calculations
uint256 internal constant HALF_EXP_SCALE = EXP_SCALE / 2
MANTISSA_ONE
Mantissa value for one
uint256 internal constant MANTISSA_ONE = EXP_SCALE
Functions
truncate
Truncates the given exp to a whole number value. For example, truncate(Exp{mantissa: 15 * EXP_SCALE}) = 15
function truncate(Exp memory exp) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
exp | Exp | The exp to truncate. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The truncated value. |
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);
divUp_
function divUp_(uint256 a, uint256 b) internal pure returns (uint256);
divUp_
function divUp_(uint256 a, Exp memory 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
Title: Liquidation helper
Author: Malda Protocol
View helper that computes whether a borrower can be liquidated and the repay amount.
Functions
getBorrowerPosition
Computes liquidation eligibility for a borrower on a market
function getBorrowerPosition(address borrower, address market)
external
view
returns (bool shouldLiquidate, uint256 repayAmount);
Parameters
| Name | Type | Description |
|---|---|---|
borrower | address | Address of the borrower |
market | address | Market address implementing ImToken |
Returns
| Name | Type | Description |
|---|---|---|
shouldLiquidate | bool | True if borrower is below collateral requirements |
repayAmount | uint256 | Max repay amount according to close factor |
IWrappedNative
Title: Wrapped native token interface
Author: Malda Protocol
Minimal interface used to wrap/unwrap native tokens (e.g., WETH)
Functions
deposit
Wraps native ETH into WETH
function deposit() external payable;
transfer
Transfers wrapped native tokens
function transfer(address to, uint256 value) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Receiver address |
value | uint256 | Amount to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | Whether the transfer succeeded |
withdraw
Unwraps wrapped native tokens back to the native coin
function withdraw(uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount to unwrap |
WrapAndSupply
Title: WrapAndSupply
Author: Malda Protocol
Wraps native coins and supplies to host or extension markets in a single call.
State Variables
WRAPPED_NATIVE
The wrapped native coin contract
IWrappedNative public immutable WRAPPED_NATIVE
Functions
constructor
Initializes the helper with the wrapped native token address
constructor(address _wrappedNative) ;
Parameters
| Name | Type | Description |
|---|---|---|
_wrappedNative | address | Wrapped native token (e.g., WETH) contract address |
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 | The minimum amount of mTokens expected |
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 extension market address |
receiver | address | The receiver |
selector | bytes4 | The host chain function selector |
_wrap
Wraps a native coin into its wrapped version
function _wrap(uint256 amountToWrap) private;
Parameters
| Name | Type | Description |
|---|---|---|
amountToWrap | uint256 | The amount of native coin to wrap |
Events
WrappedAndSupplied
Emitted when native assets are wrapped and supplied to a market
event WrappedAndSupplied(address indexed sender, address indexed receiver, address indexed market, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The caller providing native funds |
receiver | address | The account receiving the minted mTokens |
market | address | The market that received the wrapped assets |
amount | uint256 | The amount of native coin wrapped and supplied |
Errors
WrapAndSupply_AddressNotValid
Error thrown when the address is not valid
error WrapAndSupply_AddressNotValid();
WrapAndSupply_AmountNotValid
Error thrown when the amount is not valid
error WrapAndSupply_AmountNotValid();
Contents
IZkVerifier
Title: Zero-knowledge verifier interface
Author: Malda Protocol
Minimal interface to verify a Risc0 proof
Functions
verifyInput
Verify the provided Risc0 journal/seal pair
function verifyInput(bytes calldata journalEntry, bytes calldata seal) external view;
Parameters
| Name | Type | Description |
|---|---|---|
journalEntry | bytes | The Risc0 journal entry |
seal | bytes | The proof seal |
ZkVerifier
Inherits: Ownable, IZkVerifier
Title: Zero-knowledge verifier wrapper
Author: Malda Protocol
Ownable wrapper around the Risc0 verifier with configurable imageId
State Variables
verifier
Current Risc0 verifier contract
IRiscZeroVerifier public verifier
imageId
Current Risc0 image identifier
bytes32 public imageId
Functions
constructor
Initializes the verifier wrapper
constructor(address owner_, bytes32 _imageId, address _verifier) Ownable(owner_);
Parameters
| Name | Type | Description |
|---|---|---|
owner_ | address | Contract owner |
_imageId | bytes32 | Risc0 image identifier |
_verifier | address | Risc0 verifier contract address |
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 |
Events
ImageSet
Emitted when the imageId is updated
event ImageSet(bytes32 _imageId);
Parameters
| Name | Type | Description |
|---|---|---|
_imageId | bytes32 | New image identifier |
VerifierSet
Emitted when the verifier contract address is updated
event VerifierSet(address indexed oldVerifier, address indexed newVerifier);
Parameters
| Name | Type | Description |
|---|---|---|
oldVerifier | address | Previous verifier address |
newVerifier | address | New verifier address |
Errors
ZkVerifier_ImageNotValid
Error thrown when the image id is not valid
error ZkVerifier_ImageNotValid();
ZkVerifier_InputNotValid
Error thrown when the input is not valid
error ZkVerifier_InputNotValid();
ZkVerifier_VerifierNotSet
Error thrown when the verifier is not set
error ZkVerifier_VerifierNotSet();
Roles
Inherits: Ownable, IRoles
Title: Role registry
Author: Malda Protocol
Ownable registry for assigning protocol roles to contracts.
State Variables
REBALANCER
Rebalancer role
bytes32 public constant REBALANCER = keccak256("REBALANCER")
PAUSE_MANAGER
Pause manager role
bytes32 public constant PAUSE_MANAGER = keccak256("PAUSE_MANAGER")
REBALANCER_EOA
Rebalancer EOA role
bytes32 public constant REBALANCER_EOA = keccak256("REBALANCER_EOA")
GUARDIAN_PAUSE
Guardian pause role
bytes32 public constant GUARDIAN_PAUSE = keccak256("GUARDIAN_PAUSE")
CHAINS_MANAGER
Chains manager role
bytes32 public constant CHAINS_MANAGER = keccak256("CHAINS_MANAGER")
PROOF_FORWARDER
Proof forwarder role
bytes32 public constant PROOF_FORWARDER = keccak256("PROOF_FORWARDER")
PROOF_BATCH_FORWARDER
Proof batch forwarder role
bytes32 public constant PROOF_BATCH_FORWARDER = keccak256("PROOF_BATCH_FORWARDER")
SEQUENCER
Sequencer role
bytes32 public constant SEQUENCER = keccak256("SEQUENCER")
GUARDIAN_BRIDGE
Bridge guardian role
bytes32 public constant GUARDIAN_BRIDGE = keccak256("GUARDIAN_BRIDGE")
GUARDIAN_ORACLE
Oracle guardian role
bytes32 public constant GUARDIAN_ORACLE = keccak256("GUARDIAN_ORACLE")
GUARDIAN_RESERVE
Reserve guardian role
bytes32 public constant GUARDIAN_RESERVE = keccak256("GUARDIAN_RESERVE")
GUARDIAN_BORROW_CAP
Borrow cap guardian role
bytes32 public constant GUARDIAN_BORROW_CAP = keccak256("GUARDIAN_BORROW_CAP")
GUARDIAN_SUPPLY_CAP
Supply cap guardian role
bytes32 public constant GUARDIAN_SUPPLY_CAP = keccak256("GUARDIAN_SUPPLY_CAP")
GUARDIAN_BLACKLIST
Blacklist guardian role
bytes32 public constant GUARDIAN_BLACKLIST = keccak256("GUARDIAN_BLACKLIST")
_roles
Role assignment mapping: contract => role => allowed
mapping(address contractAddress => mapping(bytes32 roleIdentifier => bool allowed)) private _roles
Functions
constructor
Initializes the role registry
constructor(address owner_) Ownable(owner_);
Parameters
| Name | Type | Description |
|---|---|---|
owner_ | address | Owner address |
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. |
isAllowedFor
Checks if a contract has a given role
function isAllowedFor(address _contract, bytes32 _role) external view override returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
_contract | address | Contract address |
_role | bytes32 | Role identifier |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if allowed |
Events
Allowed
Emitted when role allowance is updated
event Allowed(address indexed _contract, bytes32 indexed _role, bool _allowed);
Parameters
| Name | Type | Description |
|---|---|---|
_contract | address | The contract being updated |
_role | bytes32 | The role identifier |
_allowed | bool | New allowance status |