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 IRoles contract for role-based permissioning.
  • Uses ZkVerifier to verify proof data before allowing withdrawals. This is using Risc0 libraries 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 IRoles contract for role-based permissioning.
  • Uses ZkVerifier to verify proof data before allowing withdrawals. This is using risc0 libraries 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)

  1. User deposits tokens into mTokenGateway (extension).

  2. Extension records this and updates its internal state hash.

  3. ZK coprocessor (Risc0) proves this transition off-chain.

  4. Proof is sent to mErc20Host, which verifies it.

  5. 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)

  1. User initiates borrow or withdraw on mErc20Host using performExtensionCall method.

  2. Contract emits a cross-chain event / message.

  3. The sequencer picks up the message.

  4. mTokenGateway finalizes 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 _underlying matches _msg.token.
  • Uses SafeApprove to 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 CREATE3 to 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

NameAddress
Deployer0x7aFcD811e32a9F221B72502bd645d4bAa56a375a
Roles0x3dc52279175EE96b6A60f6870ec4DfA417c916E3
ZkVerifier0xF3CA3C7018eA139E8B3969FF64DafDa8DF946B31
BatchSubmitter0xC03155E29276841Bc5D27653c57fb85FA6043C65
GasHelper0x3aE44aC156557D30f58E38a6796336E7eD0A3fC1
RewardDistributor0x837D67e10C0E91B58568582154222EDF4357D58E
MixedPriceOracleV40xAc028838DaF18FAD0F69a1a1e143Eb8a29b04904
Operator0x389cc3D08305C3DaAf19B2Bf2EC7dD7f66D68dA8
Pauser0x4EC99a994cC51c03d67531cdD932f231385f9618
mUSDCMock0x76daf584Cbf152c85EB2c7Fe7a3d50DaF3f5B6e6
mUSDCMock Interest0xfe2E9AB5c7b759CaeA320578844Deae1b696eb32
mwstETHMock0xD4286cc562b906589f8232335413f79d9aD42f7E
mwstETHMock Interest0x10589A75f6D84B932613633831fdE1A4b5945930

Mainnet

NameAddressChains
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 Steel ensures 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

Operator

Git Source

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

NameTypeDescription
useraddressThe user address to check

ifNotBlacklisted

Modifier to check if user is not blacklisted

modifier ifNotBlacklisted(address user) ;

Parameters

NameTypeDescription
useraddressThe 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

NameTypeDescription
_firewalladdressThe firewall address

setBlacklister

Sets the blacklist operator

function setBlacklister(address _blacklister) external onlyOwner;

Parameters

NameTypeDescription
_blacklisteraddressThe blacklist operator address

setBorrowSizeMin

Sets min borrow size per market

function setBorrowSizeMin(address[] calldata mTokens, uint256[] calldata amounts) external onlyOwner;

Parameters

NameTypeDescription
mTokensaddress[]The market address
amountsuint256[]The new size

setWhitelistedUser

Sets user whitelist status

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

Parameters

NameTypeDescription
useraddressThe user address
stateboolThe new state

setWhitelistStatus

Sets the whitelist status

function setWhitelistStatus(bool status) external onlyOwner;

Parameters

NameTypeDescription
statusboolThe new status

setRolesOperator

Sets a new Operator for the market

function setRolesOperator(address _roles) external onlyOwner;

Parameters

NameTypeDescription
_rolesaddressThe new operator address

setPriceOracle

Sets a new price oracle

Admin function to set a new price oracle

function setPriceOracle(address newOracle) external onlyOwner;

Parameters

NameTypeDescription
newOracleaddressAddress of the new oracle

setCloseFactor

Sets the closeFactor used when liquidating borrows

Admin function to set closeFactor

function setCloseFactor(uint256 newCloseFactorMantissa) external onlyOwner;

Parameters

NameTypeDescription
newCloseFactorMantissauint256New close factor, scaled by 1e18

setCollateralFactor

Sets the collateralFactor for a market

Admin function to set per-market collateralFactor

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

Parameters

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

setLiquidationIncentive

Sets liquidationIncentive

Admin function to set liquidationIncentive

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

Parameters

NameTypeDescription
marketaddressMarket address
newLiquidationIncentiveMantissauint256New liquidationIncentive scaled by 1e18

supportMarket

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

Admin function to set isListed and add support for the market

function supportMarket(address mToken) external onlyOwner;

Parameters

NameTypeDescription
mTokenaddressThe address of the market (token) to list

setOutflowVolumeTimeWindow

Sets outflow volume time window

function setOutflowVolumeTimeWindow(uint256 newTimeWindow) external onlyOwner;

Parameters

NameTypeDescription
newTimeWindowuint256The new reset time window

setOutflowTimeLimitInUSD

Sets outflow volume limit

when 0, it means there's no limit

function setOutflowTimeLimitInUSD(uint256 amount) external onlyOwner;

Parameters

NameTypeDescription
amountuint256The new limit

resetOutflowVolume

Resets outflow volume

function resetOutflowVolume() external onlyOwner;

checkOutflowVolumeLimit

Verifies outflow volume limit

function checkOutflowVolumeLimit(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The 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
    onlyFirewallApprovedAllowEOA;

Parameters

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

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

Parameters

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

setPaused

Set pause for a specific operation

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

Parameters

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

initialize

Initialize the contract

function initialize(address _rolesOperator, address _blacklistOperator, address _admin) external initializer;

Parameters

NameTypeDescription
_rolesOperatoraddressThe roles operator address
_blacklistOperatoraddressThe blacklist operator address
_adminaddressThe admin address

enterMarkets

Add assets to be included in account liquidity calculation

function enterMarkets(address[] calldata _mTokens) external override onlyFirewallApprovedAllowEOA;

Parameters

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

enterMarketsWithSender

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

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

Parameters

NameTypeDescription
_accountaddressThe account to add for

exitMarket

Removes asset from sender's account liquidity calculation

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

function exitMarket(address _mToken) external override onlyFirewallApprovedAllowEOA;

Parameters

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

Parameters

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

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

Parameters

NameTypeDescription
mTokenaddressThe market to verify the borrow against
borroweraddressThe account which would borrow the asset
borrowAmountuint256The 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

NameTypeDescription
mTokenaddressThe mToken to check
_typeImTokenOperationTypes.OperationTypethe operation type

Returns

NameTypeDescription
<none>boolpaused True if paused

getAssetsIn

Returns the assets an account has entered

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

Parameters

NameTypeDescription
_useraddressThe address of the account to pull assets for

Returns

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

checkMembership

Returns whether the given account is entered in the given asset

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

Parameters

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

Returns

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

getAllMarkets

A list of all markets

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

Returns

NameTypeDescription
mTokensaddress[]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

NameTypeDescription
mTokenaddressThe market to check if deprecated

Returns

NameTypeDescription
<none>booldeprecated True if deprecated

isMarketListed

Returns true/false

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

Parameters

NameTypeDescription
mTokenaddress

Returns

NameTypeDescription
<none>boollisted 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

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

Returns

NameTypeDescription
<none>uint256liquidity Account liquidity in excess of collateral requirements
<none>uint256shortfall 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)
    onlyAllowedUser(minter);

Parameters

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

afterMTokenMint

Validates mint and reverts on rejection. May emit logs.

function afterMTokenMint(address mToken) external view override;

Parameters

NameTypeDescription
mTokenaddressAsset being minted

beforeMTokenRedeem

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

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

Parameters

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

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

Parameters

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

beforeMTokenLiquidate

Checks if the liquidation should be allowed to occur

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

Parameters

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

beforeMTokenSeize

Checks if the seizing of assets should be allowed to occur

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

Parameters

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

getUSDValueForAllMarkets

Returns USD value for all markets

function getUSDValueForAllMarkets() external view returns (uint256 sum);

Returns

NameTypeDescription
sumuint256The total USD value of all markets

beforeRebalancing

Checks if the account should be allowed to rebalance tokens

function beforeRebalancing(address mToken) external view override;

Parameters

NameTypeDescription
mTokenaddressThe market to verify the transfer against

firewallRegister

Registers an account with the firewall

function firewallRegister(address _account) public override(HypernativeFirewallProtected);

Parameters

NameTypeDescription
_accountaddressAccount to register

_convertMarketAmountToUSDValue

Converts a market amount to USD value

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

Parameters

NameTypeDescription
amountuint256The amount to convert
mTokenaddressThe market to convert

Returns

NameTypeDescription
usdValueuint256The USD value of the amount

_activateMarket

Activates a market for a borrower

function _activateMarket(address _mToken, address borrower) private;

Parameters

NameTypeDescription
_mTokenaddressThe market to activate
borroweraddressThe 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

NameTypeDescription
mTokenaddressThe market to check
redeemeraddressThe redeemer to check
redeemTokensuint256The 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

NameTypeDescription
accountaddressThe account to get the liquidity for
mTokenModifyaddressThe market to modify
redeemTokensuint256The number of tokens to redeem
borrowAmountuint256The amount of underlying to borrow

Returns

NameTypeDescription
<none>uint256liquidity The liquidity in excess of collateral requirements
<none>uint256shortfall The shortfall below collateral requirements

_isDeprecated

Checks if a market is deprecated

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

Parameters

NameTypeDescription
mTokenaddressThe market address

Returns

NameTypeDescription
<none>booldeprecated True if the market is deprecated

Events

NewBlacklister

Emitted when blacklist operator is updated

event NewBlacklister(address indexed newBlacklister);

Parameters

NameTypeDescription
newBlacklisteraddressThe new blacklist operator address

Errors

Operator_AddressNotValid

Error thrown when address is not valid

error Operator_AddressNotValid();

OperatorStorage

Git Source

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

NameTypeDescription
useraddressAddress of the user
stateboolWhitelist 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

NameTypeDescription
mTokenaddressMarket address
_typeImTokenOperationTypes.OperationTypeOperation type paused
stateboolNew pause state

NewBorrowCap

Emitted when borrow cap for a mToken is changed

event NewBorrowCap(address indexed mToken, uint256 newBorrowCap);

Parameters

NameTypeDescription
mTokenaddressMarket address
newBorrowCapuint256New borrow cap

NewSupplyCap

Emitted when supply cap for a mToken is changed

event NewSupplyCap(address indexed mToken, uint256 newBorrowCap);

Parameters

NameTypeDescription
mTokenaddressMarket address
newBorrowCapuint256New supply cap

MarketListed

Emitted when an admin supports a market

event MarketListed(address mToken);

Parameters

NameTypeDescription
mTokenaddressMarket listed

MarketEntered

Emitted when an account enters a market

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

Parameters

NameTypeDescription
mTokenaddressMarket entered
accountaddressAccount entering

MarketExited

Emitted when an account exits a market

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

Parameters

NameTypeDescription
mTokenaddressMarket exited
accountaddressAccount exiting

NewCloseFactor

Emitted when close factor is changed by admin

event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);

Parameters

NameTypeDescription
oldCloseFactorMantissauint256Previous close factor
newCloseFactorMantissauint256New close factor

NewCollateralFactor

Emitted when a collateral factor is changed by admin

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

Parameters

NameTypeDescription
mTokenaddressMarket address
oldCollateralFactorMantissauint256Previous collateral factor
newCollateralFactorMantissauint256New collateral factor

NewLiquidationIncentive

Emitted when liquidation incentive is changed by admin

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

Parameters

NameTypeDescription
marketaddressMarket address
oldLiquidationIncentiveMantissauint256Previous incentive
newLiquidationIncentiveMantissauint256New incentive

NewPriceOracle

Emitted when price oracle is changed

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

Parameters

NameTypeDescription
oldPriceOracleaddressPrevious price oracle
newPriceOracleaddressNew price oracle

NewRolesOperator

Event emitted when rolesOperator is changed

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

Parameters

NameTypeDescription
oldRolesaddressPrevious roles operator
newRolesaddressNew roles operator

OutflowLimitUpdated

Event emitted when outflow limit is updated

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

Parameters

NameTypeDescription
senderaddressCaller updating limit
oldLimituint256Previous limit
newLimituint256New limit

OutflowTimeWindowUpdated

Event emitted when outflow reset time window is updated

event OutflowTimeWindowUpdated(uint256 oldWindow, uint256 newWindow);

Parameters

NameTypeDescription
oldWindowuint256Previous window
newWindowuint256New 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

NameTypeDescription
marketsaddress[]Markets being updated
amountsuint256[]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

Git Source

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

NameTypeDescription
_owneraddress payableThe owner address
_rolesaddressThe roles contract address

blacklist

Blacklists a user immediately (onlyOwner).

function blacklist(address user) external override onlyOwnerOrGuardian;

Parameters

NameTypeDescription
useraddressThe address to blacklist

unblacklist

Removes a user from the blacklist (onlyOwner).

function unblacklist(address user) external override onlyOwnerOrGuardian;

Parameters

NameTypeDescription
useraddressThe address to unblacklist

unblacklist

Removes a user from the blacklist (onlyOwner).

function unblacklist(address user, uint256 index) external override onlyOwnerOrGuardian;

Parameters

NameTypeDescription
useraddressThe address to unblacklist
indexuint256The index of the user in blacklist array

getBlacklistedAddresses

Returns the list of currently blacklisted addresses.

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

Returns

NameTypeDescription
<none>address[]blacklistedAddresses Array of blacklisted addresses

_addToBlacklist

Internal function to add an address to blacklist

function _addToBlacklist(address user) internal;

Parameters

NameTypeDescription
useraddressThe address to blacklist

_removeFromBlacklist

Internal function to remove an address from blacklist list

function _removeFromBlacklist(address user) internal;

Parameters

NameTypeDescription
useraddressThe address to remove

_removeFromBlacklist

Internal function to remove an address from blacklist list by index

function _removeFromBlacklist(address user, uint256 index) internal;

Parameters

NameTypeDescription
useraddressThe address to remove
indexuint256The index in the blacklist array

Contents

JumpRateModelV4

Git Source

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

NameTypeDescription
blocksPerYear_uint256The estimated number of blocks per year
baseRatePerBlock_uint256The base APR, scaled by 1e18 (can be zero)
multiplierPerBlock_uint256The rate increase in interest wrt utilization, scaled by 1e18
jumpMultiplierPerBlock_uint256The multiplier per block after utilization point
kink_uint256The utilization point where the jump multiplier applies
owner_addressThe owner of the contract
name_stringA user-friendly name for the contract

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

NameTypeDescription
baseRatePerBlock_uint256The approximate target base APR, as a mantissa (scaled by 1e18)
multiplierPerBlock_uint256The rate of increase in interest rate wrt utilization (scaled by 1e18)
jumpMultiplierPerBlock_uint256The multiplierPerBlock after hitting a specified utilization point
kink_uint256The 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

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

updateBlocksPerYear

Updates the blocksPerYear in order to make interest calculations simpler

function updateBlocksPerYear(uint256 blocksPerYear_) external onlyOwner;

Parameters

NameTypeDescription
blocksPerYear_uint256The new estimated eth blocks per year.

getSupplyRate

Returns the current supply rate per block for the market

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

Parameters

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

Returns

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

isInterestRateModel

Should return true

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

Returns

NameTypeDescription
<none>boolisModel 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

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

Returns

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

utilizationRate

Calculates the utilization rate of the market

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

Parameters

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

Returns

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

_updateBlocksPerYear

Internal function to update blocks per year

function _updateBlocksPerYear(uint256 blocksPerYear_) private;

Parameters

NameTypeDescription
blocksPerYear_uint256The 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

NameTypeDescription
basePerBlock_uint256The base rate per block (can be zero)
multiplierPerBlock_uint256The multiplier per block
jumpMultiplierPerBlock_uint256The jump multiplier per block
kink_uint256The 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

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

Contents

Contents

Contents

IAcrossReceiverV3

Git Source

Functions

handleV3AcrossMessage

handles AcrossV3 SpokePool message

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

Parameters

NameTypeDescription
tokenSentaddressthe token address received
amountuint256the token amount
relayeraddressthe relayer submitting the message (unused)
messagebytesthe custom message sent from source

IAcrossSpokePoolV3

Git Source

Functions

depositV3

FUNCTIONS *

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

depositV3Now

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

speedUpV3Deposit

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

fillV3Relay

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

fillV3RelayWithUpdatedDeposit

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

requestV3SlowFill

function requestV3SlowFill(V3RelayData calldata relayData) external;

executeV3SlowRelayLeaf

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

Events

V3FundsDeposited

EVENTS *

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

RequestedSpeedUpV3Deposit

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

FilledV3Relay

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

RequestedV3SlowFill

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

Errors

DisabledRoute

ERRORS *

error DisabledRoute();

InvalidQuoteTimestamp

error InvalidQuoteTimestamp();

InvalidFillDeadline

error InvalidFillDeadline();

InvalidExclusiveRelayer

error InvalidExclusiveRelayer();

MsgValueDoesNotMatchInputAmount

error MsgValueDoesNotMatchInputAmount();

NotExclusiveRelayer

error NotExclusiveRelayer();

NoSlowFillsInExclusivityWindow

error NoSlowFillsInExclusivityWindow();

RelayFilled

error RelayFilled();

InvalidSlowFillRequest

error InvalidSlowFillRequest();

ExpiredFillDeadline

error ExpiredFillDeadline();

InvalidMerkleProof

error InvalidMerkleProof();

InvalidChainId

error InvalidChainId();

InvalidMerkleLeaf

error InvalidMerkleLeaf();

ClaimedMerkleLeaf

error ClaimedMerkleLeaf();

InvalidPayoutAdjustmentPct

error InvalidPayoutAdjustmentPct();

WrongERC7683OrderId

error WrongERC7683OrderId();

LowLevelCallFailed

error LowLevelCallFailed(bytes data);

Structs

V3RelayData

STRUCTS *

struct V3RelayData {
    // 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

IMessageTransmitterV2

Git Source

Functions

receiveMessage

function receiveMessage(bytes calldata message, bytes calldata attestation) external returns (bool success);

Events

MessageSent

event MessageSent(bytes message);

ITokenMessangerV2

Git Source

Functions

depositForBurnWithHook

Deposits and burns tokens from sender to be minted on destination domain. Emits a DepositForBurn event.

reverts if:

  • hookData is zero-length
  • burnToken is not supported
  • destinationDomain has no TokenMessenger registered
  • transferFrom() reverts. For example, if sender's burnToken balance or approved allowance to this contract is less than amount.
  • burn() reverts. For example, if amount is 0.
  • maxFee is greater than or equal to amount.
  • MessageTransmitterV2#sendMessage reverts.
function depositForBurnWithHook(
    uint256 amount,
    uint32 destinationDomain,
    bytes32 mintRecipient,
    address burnToken,
    bytes32 destinationCaller,
    uint256 maxFee,
    uint32 minFinalityThreshold,
    bytes calldata hookData
) external;

Parameters

NameTypeDescription
amountuint256amount of tokens to burn
destinationDomainuint32destination domain to receive message on
mintRecipientbytes32address of mint recipient on destination domain, as bytes32
burnTokenaddresstoken to burn amount of, on local domain
destinationCallerbytes32authorized caller on the destination domain, as bytes32. If equal to bytes32(0), any address can broadcast the message.
maxFeeuint256maximum fee to pay on the destination domain, specified in units of burnToken
minFinalityThresholduint32
hookDatabyteshook data to append to burn message for interpretation on destination domain

Contents

IAggregatorV3

Git Source

Functions

decimals

function decimals() external view returns (uint8);

latestRoundData

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

Contents

IConnext

Git Source

Functions

xcall

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

xcall

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

xcallIntoLocal

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

domain

function domain() external view returns (uint256);

Contents

IEverclearSpoke

Git Source

Functions

newIntent

Creates a new intent

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

Parameters

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

Returns

NameTypeDescription
_intentIdbytes32The ID of the intent
_intentIntentThe intent object

Structs

Intent

struct Intent {
    uint256 val;
}

IFeeAdapter

Git Source

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

IFeeAdapterV2

Git Source

Functions

newIntent

Creates a new intent with fees

function newIntent(
    uint32[] memory _destinations,
    bytes32 _receiver,
    address _inputAsset,
    bytes32 _outputAsset,
    uint256 _amount,
    uint256 _amountOutMin,
    uint48 _ttl,
    bytes calldata _data,
    FeeParams calldata _feeParams
) external payable returns (bytes32, Intent memory);

Parameters

NameTypeDescription
_destinationsuint32[]Array of destination domains, preference ordered
_receiverbytes32Address of the receiver on the destination chain
_inputAssetaddressAddress of the input asset
_outputAssetbytes32Address of the output asset
_amountuint256Amount of input asset to use for the intent
_amountOutMinuint256Amount expected in the outputAsset
_ttluint48Time-to-live for the intent in seconds
_databytesAdditional data for the intent
_feeParamsFeeParamsFee parameters including fee amount, deadline, and signature

Returns

NameTypeDescription
<none>bytes32_intentId The ID of the created intent
<none>Intent_intent The created intent object

Structs

FeeParams

struct FeeParams {
    uint256 fee;
    uint256 deadline;
    bytes sig;
}

Intent

struct Intent {
    bytes32 initiator;
    bytes32 receiver;
    bytes32 inputAsset;
    bytes32 outputAsset;
    uint32 origin;
    uint64 nonce;
    uint48 timestamp;
    uint48 ttl;
    uint256 amount;
    uint256 amountOutMin;
    uint32[] destinations;
    bytes data;
}

Contents

Contents

MessagingParams

Git Source

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

MessagingReceipt

Git Source

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

MessagingFee

Git Source

struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}

Origin

Git Source

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

ILayerZeroEndpointV2

Git Source

Inherits: IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext

Functions

quote

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

send

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

verify

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

verifiable

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

initializable

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

lzReceive

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

clear

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

setLzToken

function setLzToken(address _lzToken) external;

lzToken

function lzToken() external view returns (address);

nativeToken

function nativeToken() external view returns (address);

setDelegate

function setDelegate(address _delegate) external;

Events

PacketSent

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

PacketVerified

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

PacketDelivered

event PacketDelivered(Origin origin, address receiver);

LzReceiveAlert

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

LzTokenSet

event LzTokenSet(address token);

DelegateSet

event DelegateSet(address sender, address delegate);

ILayerZeroOFTWrapper

Git Source

Functions

allowedTokens

The address of the alternative RsETH token mapping(address allowedToken => bool isAllowed) public allowedTokens;

function allowedTokens(address token) external view returns (bool);

deposit

Deposit altRsETH for wrsETH

function deposit(address asset, uint256 _amount) external;

Parameters

NameTypeDescription
assetaddressThe address of the token to deposit
_amountuint256The amount of tokens to deposit

withdraw

Withdraw altRseth tokens from wrsETH

function withdraw(address asset, uint256 _amount) external;

Parameters

NameTypeDescription
assetaddressThe address of the token to withdraw
_amountuint256The amount of tokens to withdraw

SendParam

Git Source

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

Git Source

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

Git Source

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

Git Source

Struct representing OFT fee details.

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

struct OFTFeeDetail {
int256 feeAmountLD; // Amount of the fee in local decimals.
string description; // Description of the fee.
}

ILayerZeroOFT

Git Source

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

NameTypeDescription
interfaceIdbytes4The interface ID.
versionuint64The version.

token

Retrieves the address of the token associated with the OFT.

function token() external view returns (address);

Returns

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

approvalRequired

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

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

function approvalRequired() external view returns (bool);

Returns

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

sharedDecimals

Retrieves the shared decimals of the OFT.

function sharedDecimals() external view returns (uint8);

Returns

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

quoteOFT

Provides a quote for OFT-related operations.

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

Parameters

NameTypeDescription
_sendParamSendParamThe parameters for the send operation.

Returns

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

quoteSend

Provides a quote for the send() operation.

MessagingFee: LayerZero msg fee

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

Parameters

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

Returns

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

send

Executes the send() operation.

MessagingReceipt: LayerZero msg receipt

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

Parameters

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

Returns

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

Events

OFTSent

event OFTSent( // 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

Git Source

Functions

allowInitializePath

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

nextNonce

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

lzReceive

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

MessageLibType

Git Source

enum MessageLibType {
Send,
Receive,
SendAndReceive
}

IMessageLib

Git Source

Inherits: IERC165

Functions

setConfig

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

getConfig

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

isSupportedEid

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

version

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

messageLibType

function messageLibType() external view returns (MessageLibType);

SetConfigParam

Git Source

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

IMessageLibManager

Git Source

Functions

registerLibrary

function registerLibrary(address _lib) external;

isRegisteredLibrary

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

getRegisteredLibraries

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

setDefaultSendLibrary

function setDefaultSendLibrary(uint32 _eid, address _newLib) external;

defaultSendLibrary

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

setDefaultReceiveLibrary

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

defaultReceiveLibrary

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

setDefaultReceiveLibraryTimeout

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

defaultReceiveLibraryTimeout

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

isSupportedEid

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

isValidReceiveLibrary

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

setSendLibrary

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

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

getSendLibrary

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

isDefaultSendLibrary

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

setReceiveLibrary

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

getReceiveLibrary

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

setReceiveLibraryTimeout

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

receiveLibraryTimeout

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

setConfig

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

getConfig

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

Events

LibraryRegistered

event LibraryRegistered(address newLib);

DefaultSendLibrarySet

event DefaultSendLibrarySet(uint32 eid, address newLib);

DefaultReceiveLibrarySet

event DefaultReceiveLibrarySet(uint32 eid, address newLib);

DefaultReceiveLibraryTimeoutSet

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

SendLibrarySet

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

ReceiveLibrarySet

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

ReceiveLibraryTimeoutSet

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

Structs

Timeout

struct Timeout {
    address lib;
    uint256 expiry;
}

IMessagingChannel

Git Source

Functions

eid

function eid() external view returns (uint32);

skip

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

nilify

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

burn

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

nextGuid

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

inboundNonce

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

outboundNonce

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

inboundPayloadHash

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

lazyInboundNonce

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

Events

InboundNonceSkipped

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

PacketNilified

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

PacketBurnt

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

IMessagingComposer

Git Source

Functions

composeQueue

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

sendCompose

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

lzCompose

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

Events

ComposeSent

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

ComposeDelivered

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

LzComposeAlert

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

IMessagingContext

Git Source

Functions

isSendingMessage

function isSendingMessage() external view returns (bool);

getSendContext

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

ILayerZeroEndpoint

Git Source

Inherits: ILayerZeroUserApplicationConfig

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

Functions

send

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

receivePayload

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

getInboundNonce

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

getOutboundNonce

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

estimateFees

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

getChainId

function getChainId() external view returns (uint16);

retryPayload

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

hasStoredPayload

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

getSendLibraryAddress

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

getReceiveLibraryAddress

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

isSendingPayload

function isSendingPayload() external view returns (bool);

isReceivingPayload

function isReceivingPayload() external view returns (bool);

getConfig

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

getSendVersion

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

getReceiveVersion

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

ILayerZeroReceiver

Git Source

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

Functions

lzReceive

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

ILayerZeroUserApplicationConfig

Git Source

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

Functions

setConfig

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

setSendVersion

function setSendVersion(uint16 _version) external;

setReceiveVersion

function setReceiveVersion(uint16 _version) external;

forceResumeReceive

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

Contents

IPohVerifier

Git Source

Functions

verify

Check if the provided signature has been signed by signer

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

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

Parameters

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

Returns

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

getSigner

Returns the signer's address

function getSigner() external view returns (address);

IBlacklister

Git Source

Title: IBlacklister

Author: Merge Layers Inc.

Interface for blacklisting addresses

Functions

blacklist

Blacklists a user immediately (onlyOwner).

function blacklist(address user) external;

Parameters

NameTypeDescription
useraddressThe address to blacklist

unblacklist

Removes a user from the blacklist (onlyOwner).

function unblacklist(address user) external;

Parameters

NameTypeDescription
useraddressThe address to unblacklist

unblacklist

Removes a user from the blacklist (onlyOwner).

function unblacklist(address user, uint256 index) external;

Parameters

NameTypeDescription
useraddressThe address to unblacklist
indexuint256The index of the user in blacklist array

getBlacklistedAddresses

Returns the list of currently blacklisted addresses.

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

Returns

NameTypeDescription
<none>address[]blacklistedAddresses Array of blacklisted addresses

isBlacklisted

Returns whether a user is currently blacklisted.

function isBlacklisted(address user) external view returns (bool);

Parameters

NameTypeDescription
useraddressThe address to check

Returns

NameTypeDescription
<none>boolisUserBlacklisted True if the user is blacklisted

Events

Blacklisted

Emitted when a user is blacklisted

event Blacklisted(address indexed user);

Parameters

NameTypeDescription
useraddressThe blacklisted address

Unblacklisted

Emitted when a user is removed from blacklist

event Unblacklisted(address indexed user);

Parameters

NameTypeDescription
useraddressThe 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

Git Source

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

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

getFee

computes fee for bridge operation

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

Parameters

NameTypeDescription
_dstChainIduint32destination chain id
_messagebytesoperation message data
_bridgeDatabytesspecific bridge data

Returns

NameTypeDescription
<none>uint256fee Computed bridge fee

IDefaultAdapter

Git Source

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

NameTypeDescription
<none>uint8decimalsCount 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

NameTypeDescription
roundIduint80Round identifier
answerint256Feed answer
startedAtuint256Round start timestamp
updatedAtuint256Round update timestamp
answeredInRounduint80The round in which the answer was computed

latestAnswer

Returns the latest answer

function latestAnswer() external view returns (int256);

Returns

NameTypeDescription
<none>int256answer Latest feed answer

latestTimestamp

Returns the latest timestamp

function latestTimestamp() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256timestamp Latest update timestamp

Structs

PriceConfig

struct PriceConfig {
    address defaultFeed; // chainlink & eOracle
    string toSymbol;
    uint256 underlyingDecimals;
}

IGasFeesHelper

Git Source

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

NameTypeDescription
dstChainIduint32Destination chain identifier

Returns

NameTypeDescription
feeuint256Gas fee amount

IInterestRateModel

Git Source

Title: IInterestRateModel

Author: Merge Layers Inc.

Interface for the interest rate contracts

Functions

isInterestRateModel

Should return true

function isInterestRateModel() external view returns (bool);

Returns

NameTypeDescription
<none>boolisModel 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

NameTypeDescription
<none>uint256The number of blocks per year

multiplierPerBlock

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

function multiplierPerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The multiplier per block

baseRatePerBlock

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

function baseRatePerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The base rate per block

jumpMultiplierPerBlock

The multiplierPerBlock after hitting a specified utilization point

function jumpMultiplierPerBlock() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The jump multiplier per block

kink

The utilization point at which the jump multiplier is applied

function kink() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The utilization point (kink)

name

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

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

Returns

NameTypeDescription
<none>stringThe name of the interest rate model

getBorrowRate

Returns the current borrow rate per block for the market

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

Parameters

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

Returns

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

getSupplyRate

Returns the current supply rate per block for the market

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

Parameters

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

Returns

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

utilizationRate

Calculates the utilization rate of the market

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

Parameters

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

Returns

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

Events

NewInterestParams

Emitted when interest rate parameters are updated

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

Parameters

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

BlocksPerYearUpdated

Emitted when blocks per year is updated

event BlocksPerYearUpdated(uint256 blocksPerYear);

Parameters

NameTypeDescription
blocksPerYearuint256The 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();

IOftMessageExecutor

Git Source

Title: IOftMessageExecutor

Author:

Interface for OFT message executor helpers used via delegatecall by bridges.

Functions

executeSend

Executes an OFT send on the bridge contract (OFT) and returns the LayerZero receipt.

function executeSend(
    address underlying,
    address bridgeContract,
    SendParam calldata params,
    MessagingFee calldata fees,
    address rebalancer,
    address refundAddress
) external payable returns (MessagingReceipt memory receipt);

Parameters

NameTypeDescription
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for the OFT send.
paramsSendParamLayerZero send parameters.
feesMessagingFeeLayerZero messaging fees.
rebalanceraddressThe rebalancer address providing the funds.
refundAddressaddressAddress that receives any excess native fee refund.

Returns

NameTypeDescription
receiptMessagingReceiptThe LayerZero messaging receipt containing the message GUID.

processUncomposed

Fallback route in case lzCompose does not execute; unwraps/forwards funds to the market.

function processUncomposed(address market, address underlying, address bridgeContract) external payable;

Parameters

NameTypeDescription
marketaddressThe market address.
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for OFT operations.

executeCompose

Executes compose handling for a market.

function executeCompose(address market, address underlying, address bridgeContract) external payable;

Parameters

NameTypeDescription
marketaddressThe market address.
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for OFT operations.

IOperatorData

Git Source

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

Git Source

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

NameTypeDescription
mTokenaddressThe 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

NameTypeDescription
mTokenaddressThe market to verify the borrow against
borroweraddressThe account which would borrow the asset
borrowAmountuint256The 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

NameTypeDescription
amountuint256New 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

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

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

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

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

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

beforeMTokenLiquidate

Checks if the liquidation should be allowed to occur

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

Parameters

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

beforeMTokenSeize

Checks if the seizing of assets should be allowed to occur

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

Parameters

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

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

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

afterMTokenMint

Validates mint and reverts on rejection. May emit logs.

function afterMTokenMint(address mToken) external view;

Parameters

NameTypeDescription
mTokenaddressAsset being minted

IOperator

Git Source

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

NameTypeDescription
_useraddressAddress to check

Returns

NameTypeDescription
<none>boolwhitelisted True if user is whitelisted

limitPerTimePeriod

Should return outflow limit

function limitPerTimePeriod() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256limit Outflow limit per period

cumulativeOutflowVolume

Should return outflow volume

function cumulativeOutflowVolume() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256volume Current outflow volume

lastOutflowResetTimestamp

Should return last reset time for outflow check

function lastOutflowResetTimestamp() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256lastReset Timestamp of last reset

outflowResetTimeWindow

Should return the outflow volume time window

function outflowResetTimeWindow() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256window Outflow window

isPaused

Returns if operation is paused

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

Parameters

NameTypeDescription
mTokenaddressThe mToken to check
_typeImTokenOperationTypes.OperationTypethe operation type

Returns

NameTypeDescription
<none>boolpaused True if paused

rolesOperator

Roles

function rolesOperator() external view returns (IRoles);

Returns

NameTypeDescription
<none>IRolesroles Roles contract

blacklistOperator

Blacklist

function blacklistOperator() external view returns (IBlacklister);

Returns

NameTypeDescription
<none>IBlacklisterblacklister Blacklist operator

oracleOperator

Oracle which gives the price of any given asset

function oracleOperator() external view returns (address);

Returns

NameTypeDescription
<none>addressoracle Oracle address

closeFactorMantissa

Multiplier used to calculate the maximum repayAmount when liquidating a borrow

function closeFactorMantissa() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256closeFactor Close factor mantissa

liquidationIncentiveMantissa

Multiplier representing the discount on collateral that a liquidator receives

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

Parameters

NameTypeDescription
marketaddressMarket address

Returns

NameTypeDescription
<none>uint256incentive Discount mantissa

isMarketListed

Returns true/false

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

Parameters

NameTypeDescription
marketaddressMarket address

Returns

NameTypeDescription
<none>boollisted True if market is listed

getAssetsIn

Returns the assets an account has entered

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

Parameters

NameTypeDescription
_useraddressThe address of the account to pull assets for

Returns

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

getAllMarkets

A list of all markets

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

Returns

NameTypeDescription
mTokensaddress[]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

NameTypeDescription
_mTokenaddressMarket address

Returns

NameTypeDescription
<none>uint256cap 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

NameTypeDescription
_mTokenaddressMarket address

Returns

NameTypeDescription
<none>uint256cap 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

NameTypeDescription
_mTokenaddressMarket address

Returns

NameTypeDescription
<none>uint256minimum 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

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

Returns

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

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

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

Returns

NameTypeDescription
liquidityuint256Account liquidity in excess of collateral requirements
shortfalluint256Account shortfall below collateral requirements

getUSDValueForAllMarkets

Returns USD value for all markets

function getUSDValueForAllMarkets() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256usdValue 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

NameTypeDescription
mTokenaddressThe market to check if deprecated

Returns

NameTypeDescription
<none>booldeprecated True if deprecated

setPaused

Set pause for a specific operation

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

Parameters

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

enterMarkets

Add assets to be included in account liquidity calculation

function enterMarkets(address[] calldata _mTokens) external;

Parameters

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

enterMarketsWithSender

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

function enterMarketsWithSender(address _account) external;

Parameters

NameTypeDescription
_accountaddressThe account to add for

exitMarket

Removes asset from sender's account liquidity calculation

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

function exitMarket(address _mToken) external;

Parameters

NameTypeDescription
_mTokenaddressThe address of the asset to be removed

IOracleOperator

Git Source

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

NameTypeDescription
mTokenaddressThe mToken to get the price of

Returns

NameTypeDescription
<none>uint256price 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

NameTypeDescription
mTokenaddressThe mToken to get the underlying price of

Returns

NameTypeDescription
<none>uint256price The underlying asset price mantissa (scaled by 1e18). Zero means unavailable.

IOwnable

Git Source

Title: IOwnable

Author: Merge Layers Inc.

Minimal ownable interface

Functions

transferOwnership

Transfers ownership to a new owner

function transferOwnership(address newOwner) external;

Parameters

NameTypeDescription
newOwneraddressAddress of the new owner

IPauser

Git Source

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

NameTypeDescription
_marketaddressthe mToken address

emergencyPauseMarketFor

Pauses a specific operation for a market

function emergencyPauseMarketFor(address _market, OperationType _pauseType) external;

Parameters

NameTypeDescription
_marketaddressthe mToken address
_pauseTypeOperationTypethe operation type

emergencyPauseAll

Pauses all operations for all registered markets

function emergencyPauseAll() external;

Events

PauseAll

Emitted when all markets are paused

event PauseAll();

MarketPaused

Emitted when a market is paused

event MarketPaused(address indexed market);

Parameters

NameTypeDescription
marketaddressThe paused market

MarketRemoved

Emitted when a market is removed

event MarketRemoved(address indexed market);

Parameters

NameTypeDescription
marketaddressThe market removed

MarketAdded

Emitted when a market is added

event MarketAdded(address indexed market, PausableType marketType);

Parameters

NameTypeDescription
marketaddressThe market added
marketTypePausableTypeThe market type

MarketPausedFor

Emitted when a specific operation is paused for a market

event MarketPausedFor(address indexed market, OperationType pauseType);

Parameters

NameTypeDescription
marketaddressThe market paused
pauseTypeOperationTypeThe 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

Git Source

Title: IRebalanceMarket

Author: Merge Layers Inc.

Interface for markets supporting rebalancing extractions.

Functions

extractForRebalancing

Extracts an amount to be used for rebalancing.

function extractForRebalancing(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256Amount to extract.

IRebalancer

Git Source

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

NameTypeDescription
bridgeaddressThe whitelisted bridge address.
_marketaddressThe market to rebalance from address.
_amountuint256The amount to rebalance.
_msgMsgThe message data.

nonce

Returns current nonce.

function nonce() external view returns (uint256 currentNonce);

Returns

NameTypeDescription
currentNonceuint256Nonce value.

isBridgeWhitelisted

Returns if a bridge implementation is whitelisted.

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

Parameters

NameTypeDescription
bridgeaddressBridge address.

Returns

NameTypeDescription
whitelistedboolTrue if whitelisted.

isDestinationWhitelisted

Returns if a destination is whitelisted.

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

Parameters

NameTypeDescription
dstIduint32Destination chain ID.

Returns

NameTypeDescription
whitelistedboolTrue if whitelisted.

isMarketWhitelisted

Returns if a market is whitelisted.

function isMarketWhitelisted(address market) external view returns (bool whitelisted);

Parameters

NameTypeDescription
marketaddressMarket address.

Returns

NameTypeDescription
whitelistedboolTrue if whitelisted.

Events

BridgeWhitelistedStatusUpdated

Emitted when bridge whitelist status changes.

event BridgeWhitelistedStatusUpdated(address indexed bridge, bool status);

Parameters

NameTypeDescription
bridgeaddressBridge address.
statusboolWhitelist 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

NameTypeDescription
bridgeaddressBridge address.
dstChainIduint32Destination chain ID.
tokenaddressToken address.
messagebytesEncoded message.
bridgeDatabytesBridge-specific data.

EthSaved

Emitted when ETH is saved back to treasury.

event EthSaved(uint256 amount);

Parameters

NameTypeDescription
amountuint256Amount saved.

MaxTransferSizeUpdated

Emitted when max transfer size is updated.

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

Parameters

NameTypeDescription
dstChainIduint32Destination chain ID.
tokenaddressToken address.
newLimituint256New limit.

MinTransferSizeUpdated

Emitted when min transfer size is updated.

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

Parameters

NameTypeDescription
dstChainIduint32Destination chain ID.
tokenaddressToken address.
newLimituint256New limit.

DestinationWhitelistedStatusUpdated

Emitted when destination whitelist status changes.

event DestinationWhitelistedStatusUpdated(uint32 indexed dstChainId, bool status);

Parameters

NameTypeDescription
dstChainIduint32Destination chain ID.
statusboolWhitelist status.

AllowedListUpdated

Emitted when allowed list is updated.

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

Parameters

NameTypeDescription
listaddress[]List of addresses.
statusboolWhitelist status.

TokensSaved

Emitted when tokens are rescued.

event TokensSaved(address indexed token, address indexed market, uint256 amount);

Parameters

NameTypeDescription
tokenaddressToken address.
marketaddressMarket address.
amountuint256Amount saved.

AllowedTokensUpdated

Emitted when allowed tokens list is updated for a bridge.

event AllowedTokensUpdated(address indexed bridge, bool status, address[] list);

Parameters

NameTypeDescription
bridgeaddressBridge address.
statusboolWhitelist status.
listaddress[]Token list.

MarketListUpdated

Emitted when the market whitelist list is updated.

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

Parameters

NameTypeDescription
listaddress[]Market list.
statusboolWhitelist status.

NewAdmin

Emitted when a new admin is set.

event NewAdmin(address indexed acc);

Parameters

NameTypeDescription
accaddressNew admin address.

SaveAddressUpdated

Emitted when the save address is updated.

event SaveAddressUpdated(address indexed save);

Parameters

NameTypeDescription
saveaddressSave address.

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

Git Source

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

Git Source

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

NameTypeDescription
mTokenaddressMarket token

notifyBorrowIndex

Updates borrow indices for all reward tokens on a market

function notifyBorrowIndex(address mToken) external;

Parameters

NameTypeDescription
mTokenaddressMarket token

notifySupplier

Notifies supplier

function notifySupplier(address mToken, address supplier) external;

Parameters

NameTypeDescription
mTokenaddressMarket token
supplieraddressSupplier address

notifyBorrower

Notifies borrower

function notifyBorrower(address mToken, address borrower) external;

Parameters

NameTypeDescription
mTokenaddressMarket token
borroweraddressBorrower address

claim

Claim tokens for holders

function claim(address[] memory holders) external;

Parameters

NameTypeDescription
holdersaddress[]The accounts to claim for

operator

The operator that rewards are distributed to

function operator() external view returns (address operatorAddress);

Returns

NameTypeDescription
operatorAddressaddressOperator address

isRewardToken

Flag to check if reward token added before

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

Parameters

NameTypeDescription
_tokenaddressThe token to check for

Returns

NameTypeDescription
isRewardTokenAddedboolTrue if token is a reward token

getRewardTokens

Added reward tokens

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

Returns

NameTypeDescription
rewardTokensaddress[]Array of reward token addresses

getBlockTimestamp

Get block timestamp

function getBlockTimestamp() external view returns (uint32 timestamp);

Returns

NameTypeDescription
timestampuint32Current 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

NameTypeDescription
rewardTokenaddressReward token address
useraddressUser address
deltaAccrueduint256Newly accrued amount
totalAccrueduint256Total accrued amount

RewardGranted

Emitted when reward is granted to a user

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
useraddressUser address
amountuint256Granted amount

SupplySpeedUpdated

Emitted when supply speed is updated

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket token
supplySpeeduint256New supply speed

BorrowSpeedUpdated

Emitted when borrow speed is updated

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket token
borrowSpeeduint256New borrow speed

OperatorSet

Emitted when operator is updated

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

Parameters

NameTypeDescription
oldOperatoraddressPrevious operator
newOperatoraddressNew operator

WhitelistedToken

Emitted when token is whitelisted

event WhitelistedToken(address indexed token);

Parameters

NameTypeDescription
tokenaddressWhitelisted token

SupplyIndexNotified

Emitted when supply index is notified

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket token

BorrowIndexNotified

Emitted when borrow index is notified

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket token

IRoles

Git Source

Title: IRoles

Author: Merge Layers Inc.

Interface for protocol role management

Functions

REBALANCER

Returns REBALANCER role

function REBALANCER() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32REBALANCER role identifier

REBALANCER_EOA

Returns REBALANCER_EOA role

function REBALANCER_EOA() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32REBALANCER_EOA role identifier

GUARDIAN_PAUSE

Returns GUARDIAN_PAUSE role

function GUARDIAN_PAUSE() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_PAUSE role identifier

GUARDIAN_BRIDGE

Returns GUARDIAN_BRIDGE role

function GUARDIAN_BRIDGE() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_BRIDGE role identifier

GUARDIAN_BORROW_CAP

Returns GUARDIAN_BORROW_CAP role

function GUARDIAN_BORROW_CAP() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_BORROW_CAP role identifier

GUARDIAN_SUPPLY_CAP

Returns GUARDIAN_SUPPLY_CAP role

function GUARDIAN_SUPPLY_CAP() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_SUPPLY_CAP role identifier

GUARDIAN_RESERVE

Returns GUARDIAN_RESERVE role

function GUARDIAN_RESERVE() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_RESERVE role identifier

PROOF_FORWARDER

Returns PROOF_FORWARDER role

function PROOF_FORWARDER() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32PROOF_FORWARDER role identifier

PROOF_BATCH_FORWARDER

Returns PROOF_BATCH_FORWARDER role

function PROOF_BATCH_FORWARDER() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32PROOF_BATCH_FORWARDER role identifier

SEQUENCER

Returns SEQUENCER role

function SEQUENCER() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32SEQUENCER role identifier

PAUSE_MANAGER

Returns PAUSE_MANAGER role

function PAUSE_MANAGER() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32PAUSE_MANAGER role identifier

CHAINS_MANAGER

Returns CHAINS_MANAGER role

function CHAINS_MANAGER() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32CHAINS_MANAGER role identifier

GUARDIAN_ORACLE

Returns GUARDIAN_ORACLE role

function GUARDIAN_ORACLE() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_ORACLE role identifier

GUARDIAN_BLACKLIST

Returns GUARDIAN_BLACKLIST role

function GUARDIAN_BLACKLIST() external view returns (bytes32 role);

Returns

NameTypeDescription
rolebytes32GUARDIAN_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

NameTypeDescription
_contractaddressThe contract address
_rolebytes32The bytes32 role

Returns

NameTypeDescription
isAllowedboolTrue if allowed

Errors

Roles_InputNotValid

Error thrown when input is not valid

error Roles_InputNotValid();

ImErc20

Git Source

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

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

redeem

Sender redeems mTokens in exchange for the underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function redeem(uint256 redeemTokens) external;

Parameters

NameTypeDescription
redeemTokensuint256The number of mTokens to redeem into underlying

redeemUnderlying

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

Accrues interest whether or not the operation succeeds, unless reverted

function redeemUnderlying(uint256 redeemAmount) external;

Parameters

NameTypeDescription
redeemAmountuint256The amount of underlying to redeem

borrow

Sender borrows assets from the protocol to their own address

function borrow(uint256 borrowAmount) external;

Parameters

NameTypeDescription
borrowAmountuint256The amount of the underlying asset to borrow

repay

Sender repays their own borrow

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

Parameters

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

Returns

NameTypeDescription
repaymentAmountuint256The actual amount repaid

repayBehalf

Sender repays a borrow belonging to borrower

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

Parameters

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

Returns

NameTypeDescription
repaymentAmountuint256The 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

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

addReserves

The sender adds to reserves

function addReserves(uint256 addAmount) external;

Parameters

NameTypeDescription
addAmountuint256The amount fo underlying token to add as reserves

ImErc20Host

Git Source

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

NameTypeDescription
mintboolMint or borrow
amountuint256The amount of underlying to be accounted for
receiveraddressThe address that will receive the mTokens or the underlying in case of borrowing
borroweraddressThe address that borrow is executed for
minAmountuint256The min amount of underlying to be accounted for

extractForRebalancing

Extract amount to be used for rebalancing operation

function extractForRebalancing(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The amount to rebalance

updateAllowedCallerStatus

Set caller status for msg.sender

function updateAllowedCallerStatus(address caller, bool status) external;

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

liquidateExternal

Mints tokens after external verification

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

Parameters

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

mintExternal

Mints tokens after external verification

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

Parameters

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

repayExternal

Repays tokens after external verification

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

Parameters

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

performExtensionCall

Initiates a withdraw operation

function performExtensionCall(uint256 actionType, uint256 amount, uint32 dstChainId) external payable;

Parameters

NameTypeDescription
actionTypeuint256The actionType param (1 - withdraw, 2 - borrow)
amountuint256The amount to withdraw
dstChainIduint32The 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

NameTypeDescription
useraddressThe user address for the proof
dstIduint32The destination chain identifier

Returns

NameTypeDescription
dataRootuint256The proof data root
journalHashuint256The proof journal hash

Events

AllowedCallerUpdated

Emitted when a user updates allowed callers

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

Parameters

NameTypeDescription
senderaddressThe caller updating permission
calleraddressThe address whose status is updated
statusboolWhether the caller is allowed

mErc20Host_ChainStatusUpdated

Emitted when a chain id whitelist status is updated

event mErc20Host_ChainStatusUpdated(uint32 indexed chainId, bool status);

Parameters

NameTypeDescription
chainIduint32The chain identifier
statusboolWhether 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

NameTypeDescription
msgSenderaddressThe caller on host chain
srcSenderaddressThe caller on source chain
userToLiquidateaddressThe user being liquidated
receiveraddressThe receiver of seized collateral
collateraladdressThe collateral market
srcChainIduint32Source chain identifier
amountuint256The 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

NameTypeDescription
msgSenderaddressThe caller on host chain
srcSenderaddressThe caller on source chain
receiveraddressThe receiver of minted tokens
chainIduint32Source chain identifier
amountuint256The 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

NameTypeDescription
msgSenderaddressThe caller on host chain
srcSenderaddressThe caller on source chain
chainIduint32Source chain identifier
amountuint256The 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

NameTypeDescription
msgSenderaddressThe caller on host chain
srcSenderaddressThe caller on source chain
positionaddressThe position being repaid
chainIduint32Source chain identifier
amountuint256The 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

NameTypeDescription
msgSenderaddressThe caller on host chain
srcSenderaddressThe caller on source chain
chainIduint32Source chain identifier
amountuint256The 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

NameTypeDescription
senderaddressThe caller initiating the borrow
dstChainIduint32Destination chain identifier
amountuint256The 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

NameTypeDescription
senderaddressThe caller initiating the withdrawal
dstChainIduint32Destination chain identifier
amountuint256The withdrawal amount

mErc20Host_GasFeeUpdated

Emitted when gas fees are updated for a dst chain

event mErc20Host_GasFeeUpdated(uint32 indexed dstChainId, uint256 amount);

Parameters

NameTypeDescription
dstChainIduint32Destination chain identifier
amountuint256The gas fee amount

mErc20Host_MintMigration

Emitted when migration mint is performed

event mErc20Host_MintMigration(address indexed receiver, uint256 amount);

Parameters

NameTypeDescription
receiveraddressReceiver of the migrated tokens
amountuint256Amount minted

mErc20Host_BorrowMigration

Emitted when migration borrow is performed

event mErc20Host_BorrowMigration(address indexed borrower, uint256 amount);

Parameters

NameTypeDescription
borroweraddressBorrower receiving funds
amountuint256Amount borrowed

mErc20Host_MigratorUpdated

Emitted when migrator address is updated

event mErc20Host_MigratorUpdated(address indexed migrator);

Parameters

NameTypeDescription
migratoraddressThe new migrator address

mErc20Host_GasHelperUpdated

Emitted when gas helper address is updated

event mErc20Host_GasHelperUpdated(address indexed helper);

Parameters

NameTypeDescription
helperaddressThe 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

Git Source

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

Git Source

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

NameTypeDescription
delegateeaddressAddress to delegate to

ImTokenMinimal

Git Source

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

NameTypeDescription
<none>stringtokenName The token name

symbol

EIP-20 token symbol for this token

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

Returns

NameTypeDescription
<none>stringtokenSymbol The token symbol

decimals

EIP-20 token decimals for this token

function decimals() external view returns (uint8);

Returns

NameTypeDescription
<none>uint8tokenDecimals The token decimals

totalSupply

Returns the value of tokens in existence.

function totalSupply() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256supply Total token supply

totalUnderlying

Returns the amount of underlying tokens

function totalUnderlying() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256underlyingAmount Total underlying amount

balanceOf

Returns the value of tokens owned by account.

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

Parameters

NameTypeDescription
accountaddressThe account to check for

Returns

NameTypeDescription
<none>uint256balance Token balance of account

underlying

Returns the underlying address

function underlying() external view returns (address);

Returns

NameTypeDescription
<none>addressunderlyingToken The underlying token address

ImToken

Git Source

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

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

Returns

NameTypeDescription
<none>boolsuccess 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

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

Returns

NameTypeDescription
<none>boolsuccess 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

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

Returns

NameTypeDescription
<none>boolsuccess Whether the approval was successful or not

balanceOfUnderlying

Returns the underlying asset balance of the owner

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

Parameters

NameTypeDescription
owneraddressThe address to query the balance of underlying assets for

Returns

NameTypeDescription
<none>uint256balance The balance of underlying assets owned by owner

totalBorrowsCurrent

Returns the total amount of borrows, accounting for interest

function totalBorrowsCurrent() external returns (uint256);

Returns

NameTypeDescription
<none>uint256totalBorrowsCurrentAmount The total amount of borrows

borrowBalanceCurrent

Returns the current borrow balance for account, accounting for interest

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

Parameters

NameTypeDescription
accountaddressThe address to query the borrow balance for

Returns

NameTypeDescription
<none>uint256borrowBalance Current borrow balance

exchangeRateCurrent

Returns the current exchange rate, with interest accrued

function exchangeRateCurrent() external returns (uint256 exchangeRate);

Returns

NameTypeDescription
exchangeRateuint256The 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

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

reduceReserves

Accrues interest and reduces reserves by transferring to admin

function reduceReserves(uint256 reduceAmount) external;

Parameters

NameTypeDescription
reduceAmountuint256Amount of reduction to reserves

rolesOperator

Roles manager

function rolesOperator() external view returns (IRoles);

Returns

NameTypeDescription
<none>IRolesroles Roles contract

admin

Administrator for this contract

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

Returns

NameTypeDescription
adminAddraddress payableAdmin address

pendingAdmin

Pending administrator for this contract

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

Returns

NameTypeDescription
pendingaddress payablePending admin address

operator

Contract which oversees inter-mToken operations

function operator() external view returns (address operatorAddr);

Returns

NameTypeDescription
operatorAddraddressOperator address

interestRateModel

Model which tells what the current interest rate should be

function interestRateModel() external view returns (address interestModel);

Returns

NameTypeDescription
interestModeladdressInterest rate model address

reserveFactorMantissa

Fraction of interest currently set aside for reserves

function reserveFactorMantissa() external view returns (uint256 reserveFactor);

Returns

NameTypeDescription
reserveFactoruint256Current reserve factor mantissa

accrualBlockTimestamp

Block timestamp that interest was last accrued at

function accrualBlockTimestamp() external view returns (uint256 timestamp);

Returns

NameTypeDescription
timestampuint256Last 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

NameTypeDescription
indexuint256Borrow index

totalBorrows

Total amount of outstanding borrows of the underlying in this market

function totalBorrows() external view returns (uint256 borrows);

Returns

NameTypeDescription
borrowsuint256Total borrows

totalReserves

Total amount of reserves of the underlying held in this market

function totalReserves() external view returns (uint256 reserves);

Returns

NameTypeDescription
reservesuint256Total 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

NameTypeDescription
accountaddressThe address to query the account snapshot for

Returns

NameTypeDescription
tokenBalanceuint256Token balance
borrowBalanceuint256Borrow balance
exchangeRateuint256Exchange rate

borrowBalanceStored

Returns the stored borrow balance for account, without accruing interest

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

Parameters

NameTypeDescription
accountaddressThe address to query the stored borrow balance for

Returns

NameTypeDescription
storedBalanceuint256The stored borrow balance

exchangeRateStored

Returns the stored exchange rate, without accruing interest

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

Returns

NameTypeDescription
exchangeRateStoredMantissauint256The stored exchange rate

getCash

Returns the total amount of available cash in the contract

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

Returns

NameTypeDescription
cashuint256The 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

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

Returns

NameTypeDescription
allowanceAmountuint256The 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

NameTypeDescription
owneraddressThe address to query the balance for

Returns

NameTypeDescription
ownerBalanceuint256The balance of tokens owned by owner

borrowRatePerBlock

Returns the current borrow rate per block

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

Returns

NameTypeDescription
borrowRateuint256The current borrow rate per block, scaled by 1e18

supplyRatePerBlock

Returns the current supply rate per block

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

Returns

NameTypeDescription
supplyRateuint256The current supply rate per block, scaled by 1e18

ImTokenGateway

Git Source

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

NameTypeDescription
amountuint256The amount to rebalance

setPaused

Set pause for a specific operation

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

Parameters

NameTypeDescription
_typeImTokenOperationTypes.OperationTypeThe pause operation type
stateboolThe pause operation status

updateAllowedCallerStatus

Set caller status for msg.sender

function updateAllowedCallerStatus(address caller, bool status) external;

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

supplyOnHost

Supply underlying to the contract

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

Parameters

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

liquidate

Liquidate a user

function liquidate(address userToLiquidate, uint256 liquidateAmount, address collateral, address receiver)
    external
    payable;

Parameters

NameTypeDescription
userToLiquidateaddressThe user to liquidate
liquidateAmountuint256The amount to liquidate
collateraladdressThe collateral address
receiveraddressThe receiver address

outHere

Extract tokens

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

Parameters

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

rolesOperator

Roles

function rolesOperator() external view returns (IRoles roles);

Returns

NameTypeDescription
rolesIRolesRoles operator contract

blacklistOperator

Blacklist operator

function blacklistOperator() external view returns (IBlacklister blacklister);

Returns

NameTypeDescription
blacklisterIBlacklisterBlacklister contract

underlying

Returns the address of the underlying token

function underlying() external view returns (address underlyingToken);

Returns

NameTypeDescription
underlyingTokenaddressThe address of the underlying token

isPaused

Returns pause state for operation

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

Parameters

NameTypeDescription
_typeImTokenOperationTypes.OperationTypeThe operation type

Returns

NameTypeDescription
pausedboolTrue if paused

accAmountIn

Returns accumulated amount in per user

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

Parameters

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
amountInuint256Accumulated amount in

accAmountOut

Returns accumulated amount out per user

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

Parameters

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
amountOutuint256Accumulated amount out

getProofData

Returns the proof data journal

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

Parameters

NameTypeDescription
useraddressUser address
dstIduint32Destination chain identifier

Returns

NameTypeDescription
dataRootuint256The proof data root
journalHashuint256The proof journal hash

gasFee

Returns the gas fee for Linea

function gasFee() external view returns (uint256 fee);

Returns

NameTypeDescription
feeuint256Gas fee amount

Events

AllowedCallerUpdated

Emitted when a user updates allowed callers

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

Parameters

NameTypeDescription
senderaddressThe caller updating permissions
calleraddressThe address whose status is updated
statusboolWhether 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

NameTypeDescription
fromaddressSender on source chain
receiveraddressReceiver on destination
accAmountInuint256Accumulated amount in
accAmountOutuint256Accumulated amount out
amountuint256Supplied amount
srcChainIduint32Source chain ID
dstChainIduint32Destination chain ID
lineaMethodSelectorbytes4Linea 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

NameTypeDescription
fromaddressSender on source chain
receiveraddressReceiver of seized collateral
amountuint256Liquidation amount
srcChainIduint32Source chain ID
dstChainIduint32Destination chain ID
userToLiquidateaddressUser being liquidated
collateraladdressCollateral 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

NameTypeDescription
msgSenderaddressSender on host chain
srcSenderaddressSender on source chain
receiveraddressReceiver of funds
accAmountInuint256Accumulated amount in
accAmountOutuint256Accumulated amount out
amountuint256Amount extracted
srcChainIduint32Source chain ID
dstChainIduint32Destination 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

NameTypeDescription
msgSenderaddressSender on host chain
srcSenderaddressSender on source chain
receiveraddressReceiver of funds
accAmountInuint256Accumulated amount in
accAmountOutuint256Accumulated amount out
amountuint256Amount skipped
srcChainIduint32Source chain ID
dstChainIduint32Destination chain ID

mTokenGateway_GasFeeUpdated

Emitted when the gas fee is updated

event mTokenGateway_GasFeeUpdated(uint256 amount);

Parameters

NameTypeDescription
amountuint256New gas fee amount

mTokenGateway_PausedState

Emitted when pause state changes

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

Parameters

NameTypeDescription
_typeImTokenOperationTypes.OperationTypeOperation type paused/unpaused
_statusboolPause status

ZkVerifierUpdated

Emitted when zk verifier is updated

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

Parameters

NameTypeDescription
oldVerifieraddressPrevious verifier
newVerifieraddressNew verifier

mTokenGateway_UserWhitelisted

Emitted when user whitelist status changes

event mTokenGateway_UserWhitelisted(address indexed user, bool status);

Parameters

NameTypeDescription
useraddressUser address
statusboolWhitelist 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

Git Source

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

Library for converting between addresses and bytes32 values.

Functions

fromLast20Bytes

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

fillLast12Bytes

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

BytesLib

Git Source

Functions

concat

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

concatStorage

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

slice

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

toAddress

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

toUint8

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

toUint16

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

toUint32

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

toUint64

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

toUint96

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

toUint128

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

toUint256

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

toBytes32

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

equal

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

equal_nonAligned

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

equalStorage

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

CREATE3

Git Source

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

Deploy to deterministic addresses without an initcode factor.

State Variables

PROXY_BYTECODE

bytes internal constant PROXY_BYTECODE = hex"67363d3d37363d34f03d5260086018f3"

PROXY_BYTECODE_HASH

bytes32 internal constant PROXY_BYTECODE_HASH = keccak256(PROXY_BYTECODE)

Functions

deploy

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

getDeployed

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

CommonLib

Git Source

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

NameTypeDescription
amountuint256Amount being transferred
dstChainIduint32Destination chain id
msgValueuint256Message value provided
allowedChainsmapping(uint32 => bool)Mapping of allowed chain ids
gasHelperIGasFeesHelperGas helper contract

checkLengthMatch

Ensures two lengths match

function checkLengthMatch(uint256 l1, uint256 l2) internal pure;

Parameters

NameTypeDescription
l1uint256First length
l2uint256Second length

checkLengthMatch

Ensures three lengths match

function checkLengthMatch(uint256 l1, uint256 l2, uint256 l3) internal pure;

Parameters

NameTypeDescription
l1uint256First length
l2uint256Second length
l3uint256Third length

computeSum

Computes sum of an array

function computeSum(uint256[] calldata values) internal pure returns (uint256 sum);

Parameters

NameTypeDescription
valuesuint256[]Array of values

Returns

NameTypeDescription
sumuint256Total 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

Git Source

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

NameTypeDescription
accountaddressThe account to register.
isStrictModeboolWhether strict mode is enabled.

validateBlacklistedAccountInteraction

Validates the blacklisted account interaction.

function validateBlacklistedAccountInteraction(address sender) external;

Parameters

NameTypeDescription
senderaddressThe sender of the transaction.

validateForbiddenAccountInteraction

Validates the forbidden account interaction.

function validateForbiddenAccountInteraction(address sender) external view;

Parameters

NameTypeDescription
senderaddressThe sender of the transaction.

validateForbiddenContextInteraction

Validates the forbidden context interaction.

function validateForbiddenContextInteraction(address origin, address sender) external view;

Parameters

NameTypeDescription
originaddressThe origin of the transaction/context.
senderaddressThe sender of the transaction.

HypernativeFirewallProtected

Git Source

Title: HypernativeFirewallProtected

Author: Merge Layers Inc.

Abstract contract that provides firewall protection for inheriting contracts.

Inherited from Hypernative and refactored for our needs without changing core behavior.

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

onlyFirewallAdmin

modifier onlyFirewallAdmin() ;

onlyFirewallApprovedAllowEOA

Modifier to restrict access to only approved firewall addresses and EOAs.

modifier onlyFirewallApprovedAllowEOA() ;

changeFirewallAdmin

Changes the firewall admin.

function changeFirewallAdmin(address _newAdmin) external onlyFirewallAdmin;

Parameters

NameTypeDescription
_newAdminaddressThe new firewall admin address.

firewallRegister

Registers an account with the firewall.

function firewallRegister(address _account) public virtual;

Parameters

NameTypeDescription
_accountaddressThe account to register.

setFirewall

Sets the firewall address.

Admin only. Set to address(0) to revoke firewall usage.

function setFirewall(address _firewall) public onlyFirewallAdmin;

Parameters

NameTypeDescription
_firewalladdressThe new firewall address.

setIsStrictMode

Sets strict mode.

function setIsStrictMode(bool _mode) public onlyFirewallAdmin;

Parameters

NameTypeDescription
_modeboolWhether strict mode is enabled.

hypernativeFirewallAdmin

Returns the firewall admin address.

function hypernativeFirewallAdmin() public view returns (address admin_);

Returns

NameTypeDescription
admin_addressThe firewall admin.

_firewallGate

Validates the firewall gate.

function _firewallGate(address sender) internal;

Parameters

NameTypeDescription
senderaddressThe sender of the transaction.

_initHypernativeFirewall

Initializes the firewall.

function _initHypernativeFirewall(address _firewall, address _admin) internal;

Parameters

NameTypeDescription
_firewalladdressThe firewall address.
_adminaddressThe firewall admin address.

_changeFirewallAdmin

Changes the firewall admin.

function _changeFirewallAdmin(address _newAdmin) internal;

Parameters

NameTypeDescription
_newAdminaddressThe new firewall admin address.

_onlyFirewallAdmin

Modifier to restrict access to only approved firewall addresses and EOAs.

function _onlyFirewallAdmin() internal view;

_getAddressBySlot

Returns the address by slot.

function _getAddressBySlot(bytes32 slot) internal view returns (address addr);

Parameters

NameTypeDescription
slotbytes32The slot to get the address from.

Returns

NameTypeDescription
addraddressThe address.

_getValueBySlot

Returns the value by slot.

function _getValueBySlot(bytes32 _slot) internal view returns (uint256 value);

Parameters

NameTypeDescription
_slotbytes32The slot to get the value from.

Returns

NameTypeDescription
valueuint256The value.

_setAddressBySlot

Sets the address by slot.

function _setAddressBySlot(bytes32 slot, address newAddress) private;

Parameters

NameTypeDescription
slotbytes32The slot to set the address to.
newAddressaddressThe new address.

_setValueBySlot

Sets the value by slot.

function _setValueBySlot(bytes32 _slot, uint256 _value) private;

Parameters

NameTypeDescription
_slotbytes32The slot to set the value to.
_valueuint256The new value.

_hypernativeFirewallIsStrictMode

Returns whether strict mode is enabled.

function _hypernativeFirewallIsStrictMode() private view returns (bool);

Returns

NameTypeDescription
<none>boolTrue if strict mode is enabled, false otherwise.

_hypernativeFirewall

Returns the firewall address.

function _hypernativeFirewall() private view returns (address);

Returns

NameTypeDescription
<none>addressThe firewall address.

Events

FirewallAdminChanged

Emitted when the firewall admin changes.

event FirewallAdminChanged(address indexed previousAdmin, address indexed newAdmin);

Parameters

NameTypeDescription
previousAdminaddressThe previous firewall admin.
newAdminaddressThe new firewall admin.

FirewallAddressChanged

Emitted when the firewall address is changed.

event FirewallAddressChanged(address indexed previousFirewall, address indexed newFirewall);

Parameters

NameTypeDescription
previousFirewalladdressThe previous firewall address.
newFirewalladdressThe new firewall address.

Errors

HypernativeFirewallProtected_NotAdmin

error HypernativeFirewallProtected_NotAdmin();

HypernativeFirewallProtected_NotValid

error HypernativeFirewallProtected_NotValid();

LZOptions

Git Source

Title: LZOptions

Author: Malda Protocol

LZ Options implementation

State Variables

TYPE_3

uint16 internal constant TYPE_3 = 3

WORKER_ID

uint8 internal constant WORKER_ID = 1

OPTION_TYPE_LZRECEIVE

uint8 internal constant OPTION_TYPE_LZRECEIVE = 1

OPTION_TYPE_LZCOMPOSE

uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3

OPTION_TYPE_ORDERED_EXECUTION

uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4

Functions

newOptions

Creates new options.

function newOptions() internal pure returns (bytes memory);

Returns

NameTypeDescription
<none>bytesoptions The options.

addExecutorLzReceiveOption

Adds a LZ Receive option.

function addExecutorLzReceiveOption(bytes memory options, uint128 gas, uint128 value)
    internal
    pure
    returns (bytes memory);

Parameters

NameTypeDescription
optionsbytesThe options.
gasuint128The gas.
valueuint128The value.

Returns

NameTypeDescription
<none>bytesoptions The options.

addExecutorLzComposeOption

Adds a LZ Compose option.

function addExecutorLzComposeOption(bytes memory options, uint16 index, uint128 gas, uint128 value)
    internal
    pure
    returns (bytes memory);

Parameters

NameTypeDescription
optionsbytesThe options.
indexuint16The index.
gasuint128The gas.
valueuint128The value.

Returns

NameTypeDescription
<none>bytesoptions The options.

addExecutorOrderedExecutionOption

Adds an Ordered Execution option.

function addExecutorOrderedExecutionOption(bytes memory options) internal pure returns (bytes memory);

Parameters

NameTypeDescription
optionsbytesThe options.

Returns

NameTypeDescription
<none>bytesoptions The options.

IToken

Git Source

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

NameTypeDescription
spenderaddressAddress allowed to spend
amountuint256Allowance amount

Returns

NameTypeDescription
<none>boolsuccess True if approve succeeded

SafeApprove

Git Source

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

NameTypeDescription
tokenaddressToken to approve
toaddressSpender address
valueuint256New 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

Git Source

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

NameTypeDescription
journalDatabytesPacked journal bytes

Returns

NameTypeDescription
senderaddressJournal sender
marketaddressMarket address
accAmountInuint256Accumulated amount in
accAmountOutuint256Accumulated amount out
chainIduint32Source chain id
dstChainIduint32Destination chain id
l1InclusionboolWhether 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

NameTypeDescription
senderaddressJournal sender
marketaddressMarket address
accAmountInuint256Accumulated amount in
accAmountOutuint256Accumulated amount out
chainIduint32Source chain id
dstChainIduint32Destination chain id
l1InclusionboolWhether L1 inclusion is required

Returns

NameTypeDescription
<none>bytesPacked 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

Contents

mTokenGateway

Git Source

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

NameTypeDescription
_typeOperationTypeThe operation type

onlyAllowedUser

Modifier to restrict access to only allowed users

modifier onlyAllowedUser(address user) ;

Parameters

NameTypeDescription
useraddressThe user address

ifNotBlacklisted

Modifier to restrict access to only not blacklisted users

modifier ifNotBlacklisted(address user) ;

Parameters

NameTypeDescription
useraddressThe 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

NameTypeDescription
_owneraddress payableOwner address
_underlyingaddressUnderlying token
_rolesaddressRoles contract
_blacklisteraddressBlacklister contract
zkVerifier_addressZK verifier

initFirewall

Initializes the firewall configuration

function initFirewall(address _firewall) external onlyOwner;

Parameters

NameTypeDescription
_firewalladdressFirewall address to set

setBlacklister

Sets the blacklister contract

function setBlacklister(address _blacklister) external onlyOwner;

Parameters

NameTypeDescription
_blacklisteraddressAddress of the blacklister

setWhitelistedUser

Sets user whitelist status

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

Parameters

NameTypeDescription
useraddressThe user address
stateboolThe 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 onlyFirewallApprovedAllowEOA;

extractForRebalancing

Extract amount to be used for rebalancing operation

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

Parameters

NameTypeDescription
amountuint256The amount to rebalance

setGasFee

Sets the gas fee

function setGasFee(uint256 amount) external onlyOwner;

Parameters

NameTypeDescription
amountuint256the new gas fee

withdrawGasFees

Withdraw gas received so far

function withdrawGasFees(address payable receiver) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
receiveraddress payablethe receiver address

updateZkVerifier

Updates IZkVerifier address

function updateZkVerifier(address _zkVerifier) external onlyOwner;

Parameters

NameTypeDescription
_zkVerifieraddressthe verifier address

updateAllowedCallerStatus

Set caller status for msg.sender

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

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

supplyOnHost

Supply underlying to the contract

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

Parameters

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

liquidate

Liquidate a user

function liquidate(address userToLiquidate, uint256 liquidateAmount, address collateral, address receiver)
    external
    payable
    override
    liquidateChecks
    ifNotBlacklisted(receiver)
    onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
userToLiquidateaddressThe user to liquidate
liquidateAmountuint256The amount to liquidate
collateraladdressThe collateral address
receiveraddressThe 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)
    onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
journalDatabytesThe supplied journal
sealbytesThe seal address
amountsuint256[]The amounts to withdraw for each journal
receiveraddressThe 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

NameTypeDescription
useraddressUser address
<none>uint32

Returns

NameTypeDescription
<none>uint256dataRoot The proof data root
<none>uint256journalHash The proof journal hash

firewallRegister

Registers an account in the firewall

function firewallRegister(address _account) public override(HypernativeFirewallProtected);

Parameters

NameTypeDescription
_accountaddressAccount to register

_takeIn

Handles inbound transfers and accounting

function _takeIn(address asset, uint256 amount, address receiver) private;

Parameters

NameTypeDescription
assetaddressAsset address
amountuint256Amount to transfer
receiveraddressReceiver address

_outHere

Processes an outgoing transfer based on journal data

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

Parameters

NameTypeDescription
journalDatabytesEncoded journal payload
amountuint256Amount to transfer
receiveraddressReceiver address override

_verifyProof

Verifies proof data and inclusion constraints

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

Parameters

NameTypeDescription
journalDatabytesEncoded journals
sealbytesProof seal data

_checkSender

Validates sender permissions for proof forwarding

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

Parameters

NameTypeDescription
msgSenderaddressCaller address
srcSenderaddressSource sender encoded in journal

_getSequencerRole

Returns sequencer role identifier

function _getSequencerRole() private view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role id

_getBatchProofForwarderRole

Returns batch proof forwarder role identifier

function _getBatchProofForwarderRole() private view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role id

_getProofForwarderRole

Returns proof forwarder role identifier

function _getProofForwarderRole() private view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role id

_isAllowedFor

Checks if sender has a specific role

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

Parameters

NameTypeDescription
_senderaddressSender address
rolebytes32Role to check

Returns

NameTypeDescription
<none>boolTrue if allowed

Contents

mErc20Host

Git Source

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

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

initFirewall

Inits firewall

function initFirewall(address _firewall) external onlyAdmin;

Parameters

NameTypeDescription
_firewalladdressThe firewall address

resetMarket

Resets the market state

function resetMarket() external onlyAdmin;

updateAllowedChain

Updates an allowed chain status

function updateAllowedChain(uint32 _chainId, bool status_) external;

Parameters

NameTypeDescription
_chainIduint32the chain id
status_boolthe new status

extractForRebalancing

Extract amount to be used for rebalancing operation

function extractForRebalancing(uint256 amount) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
amountuint256The amount to rebalance

setMigrator

Sets the migrator address

function setMigrator(address _migrator) external onlyAdmin;

Parameters

NameTypeDescription
_migratoraddressThe new migrator address

setGasHelper

Sets the gas fees helper address

function setGasHelper(address _helper) external onlyAdmin;

Parameters

NameTypeDescription
_helperaddressThe new helper address

withdrawGasFees

Withdraw gas received so far

function withdrawGasFees(address payable receiver) external;

Parameters

NameTypeDescription
receiveraddress payablethe receiver address

updateZkVerifier

Updates IZkVerifier address

function updateZkVerifier(address _zkVerifier) external onlyAdmin;

Parameters

NameTypeDescription
_zkVerifieraddressthe verifier address

updateAllowedCallerStatus

Set caller status for msg.sender

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

Parameters

NameTypeDescription
calleraddressThe caller address
statusboolThe status to set for caller

liquidateExternal

Mints tokens after external verification

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

Parameters

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

mintExternal

Mints tokens after external verification

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

Parameters

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

repayExternal

Repays tokens after external verification

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

Parameters

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

performExtensionCall

Initiates a withdraw operation

function performExtensionCall(uint256 actionType, uint256 amount, uint32 dstChainId)
    external
    payable
    override
    onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
actionTypeuint256The actionType param (1 - withdraw, 2 - borrow)
amountuint256The amount to withdraw
dstChainIduint32The 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
    onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
isMintbool
amountuint256The amount of underlying to be accounted for
receiveraddressThe address that will receive the mTokens or the underlying in case of borrowing
borroweraddressThe address that borrow is executed for
minAmountuint256The 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

NameTypeDescription
useraddressThe user address for the proof
dstIduint32The destination chain identifier

Returns

NameTypeDescription
<none>uint256dataRoot The proof data root
<none>uint256journalHash 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

NameTypeDescription
singleJournalbytesEncoded journal entry
userToLiquidateaddressAccount to be liquidated
liquidateAmountuint256Amount to liquidate
collateraladdressCollateral address to seize
receiveraddressReceiver 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

NameTypeDescription
singleJournalbytesEncoded journal entry
mintAmountuint256Amount to mint
minAmountOutuint256Minimum amount out allowed
receiveraddressReceiver address

_repayExternal

Processes a single repayExternal call from decoded journal

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

Parameters

NameTypeDescription
singleJournalbytesEncoded journal entry
repayAmountuint256Amount to repay
receiveraddressReceiver address

_checkOutflow

Validates outflow limits via defender

function _checkOutflow(uint256 amount) internal;

Parameters

NameTypeDescription
amountuint256Amount to check

_onlyAdminOrRole

Ensures caller is admin or has specific role

function _onlyAdminOrRole(bytes32 _role) internal view;

Parameters

NameTypeDescription
_rolebytes32Role identifier to check

_checkJournalData

Performs basic proof call checks

function _checkJournalData(uint32 dstChainId, uint32 chainId, address market, address sender) internal view;

Parameters

NameTypeDescription
dstChainIduint32Destination chain id
chainIduint32Source chain id
marketaddressMarket address encoded in proof
senderaddressSender extracted from proof

_isAllowedFor

Checks if sender has specified role

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

Parameters

NameTypeDescription
_senderaddressAddress to check
rolebytes32Role identifier

Returns

NameTypeDescription
<none>boolTrue if allowed

_getChainsManagerRole

Retrieves chains manager role id

function _getChainsManagerRole() internal view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role identifier

_getProofForwarderRole

Retrieves proof forwarder role id

function _getProofForwarderRole() internal view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role identifier

_getBatchProofForwarderRole

Retrieves batch proof forwarder role id

function _getBatchProofForwarderRole() internal view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role identifier

_getSequencerRole

Retrieves sequencer role id

function _getSequencerRole() internal view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Role identifier

_verifyProof

Verifies proof data and checks inclusion constraints

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

Parameters

NameTypeDescription
journalDatabytesEncoded journal data
sealbytesZk proof seal

_decodeJournals

Decodes encoded journals data

function _decodeJournals(bytes calldata data) internal pure returns (bytes[] memory);

Parameters

NameTypeDescription
databytesEncoded journal data

Returns

NameTypeDescription
<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

Git Source

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

NameTypeDescription
_rolesaddressThe roles contract address
_zkVerifieraddressThe ZkVerifier contract address
owner_addressThe owner address

updateZkVerifier

Updates IZkVerifier address

function updateZkVerifier(address _zkVerifier) external onlyOwner;

Parameters

NameTypeDescription
_zkVerifieraddressthe verifier address

batchProcess

Execute multiple operations in a single transaction

function batchProcess(BatchProcessMsg calldata data) external;

Parameters

NameTypeDescription
dataBatchProcessMsgThe batch process message data

_verifyProof

Verifies the proof using ZkVerifier

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

Parameters

NameTypeDescription
journalDatabytesThe journal data to verify
sealbytesThe seal data for verification

Events

BatchProcessFailed

Event emitted when batch process fails

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

Parameters

NameTypeDescription
initHashbytes32The initialization hash
receiveraddressThe receiver address
mTokenaddressThe mToken address
amountuint256The amount
minAmountOutuint256The minimum amount out
selectorbytes4The function selector
reasonbytesThe failure reason

BatchProcessSuccess

Event emitted when batch process succeeds

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

Parameters

NameTypeDescription
initHashbytes32The initialization hash
receiveraddressThe receiver address
mTokenaddressThe mToken address
amountuint256The amount
minAmountOutuint256The minimum amount out
selectorbytes4The function selector

ZkVerifierUpdated

Event emitted when ZkVerifier is updated

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

Parameters

NameTypeDescription
oldVerifieraddressThe old verifier address
newVerifieraddressThe 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

NameTypeDescription
receiversaddress[]Funds receivers
journalDatabytesEncoded journal data
sealbytesSeal data for verification
mTokensaddress[]Array of mToken addresses
amountsuint256[]Array of amounts for each operation
minAmountsOutuint256[]Array of minimum output amounts
selectorsbytes4[]Array of function selectors for each operation
initHashesbytes32[]Array of initial hashes for journals
startIndexuint256Start index for processing journals
userToLiquidateaddress[]Array of users to liquidate (for liquidateExternal operations)
collateraladdress[]Array of collateral addresses (for liquidateExternal operations)

mErc20

Git Source

Inherits: mToken, ImErc20

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

NameTypeDescription
tokenIERC20The address of the ERC-20 token to sweep
amountuint256The 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 onlyFirewallApprovedAllowEOA;

Parameters

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

redeem

Sender redeems mTokens in exchange for the underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

function redeem(uint256 redeemTokens) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
redeemTokensuint256The number of mTokens to redeem into underlying

redeemUnderlying

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

Accrues interest whether or not the operation succeeds, unless reverted

function redeemUnderlying(uint256 redeemAmount) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
redeemAmountuint256The amount of underlying to redeem

borrow

Sender borrows assets from the protocol to their own address

function borrow(uint256 borrowAmount) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
borrowAmountuint256The amount of the underlying asset to borrow

repay

Sender repays their own borrow

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

Parameters

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

Returns

NameTypeDescription
<none>uint256repaymentAmount The actual amount repaid

repayBehalf

Sender repays a borrow belonging to borrower

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

Parameters

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

Returns

NameTypeDescription
<none>uint256repaymentAmount 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
    onlyFirewallApprovedAllowEOA;

Parameters

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

addReserves

The sender adds to reserves

function addReserves(uint256 addAmount) external;

Parameters

NameTypeDescription
addAmountuint256The amount fo underlying token to add as reserves

_initializeMErc20

Initialize the new money market

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

Parameters

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

_doTransferIn

Performs a transfer in, reverting upon failure

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

Parameters

NameTypeDescription
fromaddressSender address
amountuint256Amount to transfer

Returns

NameTypeDescription
<none>uint256Amount actually transferred to the protocol

_doTransferOut

Performs a transfer out to a recipient

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

Parameters

NameTypeDescription
toaddress payableRecipient address
amountuint256Amount 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

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

Errors

mErc20_TokenNotValid

Error thrown when token is not valid

error mErc20_TokenNotValid();

mErc20Immutable

Git Source

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

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

Errors

mErc20Immutable_AdminNotValid

Error thrown when admin is not valid

error mErc20Immutable_AdminNotValid();

mErc20Upgradable

Git Source

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

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

Errors

mErc20Upgradable_AdminNotValid

Error thrown when the admin is not valid

error mErc20Upgradable_AdminNotValid();

mToken

Git Source

Inherits: mTokenConfiguration, ReentrancyGuard, HypernativeFirewallProtected

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
    onlyFirewallApprovedAllowEOA
    returns (bool);

Parameters

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

Returns

NameTypeDescription
<none>boolsuccess 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
    onlyFirewallApprovedAllowEOA
    nonReentrant
    returns (bool);

Parameters

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

Returns

NameTypeDescription
<none>boolsuccess 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

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

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
<none>uint256totalBorrowsCurrentAmount 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

NameTypeDescription
accountaddressThe address to query the borrow balance for

Returns

NameTypeDescription
<none>uint256borrowBalance 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

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

reduceReserves

Accrues interest and reduces reserves by transferring to admin

function reduceReserves(uint256 reduceAmount) external override nonReentrant;

Parameters

NameTypeDescription
reduceAmountuint256Amount of reduction to reserves

balanceOfUnderlying

Returns the underlying asset balance of the owner

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

Parameters

NameTypeDescription
owneraddressThe address to query the balance of underlying assets for

Returns

NameTypeDescription
<none>uint256balance 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

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

Returns

NameTypeDescription
<none>uint256allowanceAmount 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

NameTypeDescription
owneraddress

Returns

NameTypeDescription
<none>uint256balance 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

NameTypeDescription
accountaddressThe address to query the account snapshot for

Returns

NameTypeDescription
tokenBalanceuint256Token balance
borrowBalanceuint256Borrow balance
exchangeRateuint256Exchange rate

borrowRatePerBlock

Returns the current borrow rate per block

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

Returns

NameTypeDescription
<none>uint256borrowRate 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

NameTypeDescription
<none>uint256supplyRate 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

NameTypeDescription
accountaddressThe address to query the stored borrow balance for

Returns

NameTypeDescription
<none>uint256storedBalance The stored borrow balance

getCash

Returns the total amount of available cash in the contract

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

Returns

NameTypeDescription
<none>uint256cash The total amount of cash

exchangeRateStored

Returns the stored exchange rate, without accruing interest

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

Returns

NameTypeDescription
<none>uint256exchangeRateStoredMantissa The stored exchange rate

exchangeRateCurrent

Returns the current exchange rate, with interest accrued

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

Returns

NameTypeDescription
<none>uint256exchangeRate 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

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

_mint

Sender supplies assets into the market and receives mTokens in exchange

Accrues interest whether or not the operation succeeds, unless reverted

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

Parameters

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

_redeem

Sender redeems mTokens in exchange for the underlying asset

Accrues interest whether or not the operation succeeds, unless reverted

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

Parameters

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

Returns

NameTypeDescription
underlyingAmountuint256Amount 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

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

_borrow

Sender borrows assets from the protocol to their own address

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

Parameters

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

_borrowWithReceiver

Sender borrows assets from the protocol to their own address

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

Parameters

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

_repay

Sender repays their own borrow

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

Parameters

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

Returns

NameTypeDescription
<none>uint256actualRepay Amount actually repaid

_repayBehalf

Sender repays a borrow belonging to borrower

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

Parameters

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

Returns

NameTypeDescription
<none>uint256actualRepay 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

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

_seize

Transfers collateral tokens (this market) to the liquidator.

Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another mToken. 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

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

_addReserves

Accrues interest and reduces reserves by transferring from msg.sender

function _addReserves(uint256 addAmount) internal nonReentrant;

Parameters

NameTypeDescription
addAmountuint256Amount of addition to reserves

__liquidate

The liquidator liquidates the borrowers collateral.

The collateral seized is transferred to the liquidator.

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

Parameters

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

_borrowBalanceStored

Return the borrow balance of account based on stored data

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

Parameters

NameTypeDescription
accountaddressThe address whose balance should be calculated

Returns

NameTypeDescription
<none>uint256borrowBalance 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

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

Returns

NameTypeDescription
<none>uint256returns the actual repay amount

__borrow

Users borrow assets from the protocol to their own address

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

Parameters

NameTypeDescription
borroweraddress payableBorrower address
receiveraddress payableReceiver address
borrowAmountuint256The amount of the underlying asset to borrow
doTransferboolIf 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

NameTypeDescription
redeemeraddress payableAddress redeeming
redeemTokensInuint256Number of tokens to redeem (if non-zero)
redeemAmountInuint256Underlying amount to redeem (if non-zero)
doTransferboolIf an actual transfer should be performed

Returns

NameTypeDescription
redeemAmountuint256Underlying 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

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

_transferTokens

Transfer tokens tokens from src to dst by spender

Called by both transfer and transferFrom internally

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

Parameters

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

__calculateSeizeTokens

Calculates seize token amount for liquidation

function __calculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint256 actualRepayAmount)
    private
    view
    returns (uint256 seizeTokens);

Parameters

NameTypeDescription
mTokenBorrowedaddressThe market of the borrowed asset
mTokenCollateraladdressThe market of the collateral asset
actualRepayAmountuint256Actual amount repaid

Returns

NameTypeDescription
seizeTokensuint256Amount of collateral tokens to seize

mTokenConfiguration

Git Source

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

NameTypeDescription
_operatoraddressThe new operator address

setRolesOperator

Sets a new Roles operator for the market

function setRolesOperator(address _roles) external onlyAdmin;

Parameters

NameTypeDescription
_rolesaddressThe roles contract address

setInterestRateModel

Accrues interest and updates the interest rate model using _setInterestRateModelFresh

function setInterestRateModel(address newInterestRateModel) external onlyAdmin;

Parameters

NameTypeDescription
newInterestRateModeladdressThe new interest rate model to use

setBorrowRateMaxMantissa

Sets the maximum borrow rate mantissa

function setBorrowRateMaxMantissa(uint256 maxMantissa) external onlyAdmin;

Parameters

NameTypeDescription
maxMantissauint256The 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

NameTypeDescription
newReserveFactorMantissauint256The 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

NameTypeDescription
newPendingAdminaddress payableNew pending admin.

acceptAdmin

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

Admin function for pending admin to accept role and update admin

function acceptAdmin() external;

_setInterestRateModel

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

Admin function to update the interest rate model

function _setInterestRateModel(address newInterestRateModel) internal;

Parameters

NameTypeDescription
newInterestRateModeladdressThe new interest rate model to use

_setOperator

Sets the Operator contract address

function _setOperator(address _operator) internal;

Parameters

NameTypeDescription
_operatoraddressThe operator address

mTokenStorage

Git Source

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

NameTypeDescription
fromaddressSender address
amountuint256Amount to transfer in

Returns

NameTypeDescription
<none>uint256Amount actually transferred to the protocol

_doTransferOut

Performs a transfer out to recipient

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

Parameters

NameTypeDescription
toaddress payableRecipient address
amountuint256Amount 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

NameTypeDescription
<none>uint256calculated exchange rate scaled by 1e18

_getBlockTimestamp

Retrieves current block timestamp (virtual for tests)

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

Returns

NameTypeDescription
<none>uint256Current 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

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

Events

NewRolesOperator

Event emitted when rolesOperator is changed

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

Parameters

NameTypeDescription
oldRolesaddressPrevious roles contract
newRolesaddressNew roles contract

NewOperator

Event emitted when Operator is changed

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

Parameters

NameTypeDescription
oldOperatoraddressPrevious operator address
newOperatoraddressNew operator address

NewPendingAdmin

Event emitted when pending admin is updated

event NewPendingAdmin(address indexed pendingAdmin);

Parameters

NameTypeDescription
pendingAdminaddressThe new pending admin address

AdminAccepted

Event emitted when admin is accepted

event AdminAccepted(address indexed admin);

Parameters

NameTypeDescription
adminaddressThe new admin address

Transfer

EIP20 Transfer event

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

Parameters

NameTypeDescription
fromaddressSender address
toaddressReceiver address
amountuint256Amount transferred

Approval

EIP20 Approval event

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

Parameters

NameTypeDescription
owneraddressToken owner
spenderaddressSpender address
amountuint256Allowed amount

AccrueInterest

Event emitted when interest is accrued

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

Parameters

NameTypeDescription
cashPrioruint256Cash prior to accrual
interestAccumulateduint256Interest accumulated during accrual
borrowIndexuint256New borrow index
totalBorrowsuint256Total borrows after accrual

Mint

Event emitted when tokens are minted

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

Parameters

NameTypeDescription
minteraddressAddress initiating mint
receiveraddressReceiver of minted tokens
mintAmountuint256Amount of underlying supplied
mintTokensuint256Amount of mTokens minted

Redeem

Event emitted when tokens are redeemed

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

Parameters

NameTypeDescription
redeemeraddressAddress redeeming tokens
redeemAmountuint256Amount of underlying redeemed
redeemTokensuint256Number of tokens redeemed

Borrow

Event emitted when underlying is borrowed

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

Parameters

NameTypeDescription
borroweraddressBorrower address
borrowAmountuint256Amount borrowed
accountBorrowsuint256Account borrow balance
totalBorrowsuint256Total 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

NameTypeDescription
payeraddressAddress paying back
borroweraddressBorrower whose debt is reduced
repayAmountuint256Amount repaid
accountBorrowsuint256Borrower's balance after repay
totalBorrowsuint256Total 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

NameTypeDescription
liquidatoraddressLiquidator address
borroweraddressBorrower being liquidated
repayAmountuint256Amount repaid
mTokenCollateraladdressCollateral market
seizeTokensuint256Tokens seized

NewMarketInterestRateModel

Event emitted when interestRateModel is changed

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

Parameters

NameTypeDescription
oldInterestRateModeladdressPrevious interest rate model
newInterestRateModeladdressNew interest rate model

NewReserveFactor

Event emitted when the reserve factor is changed

event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);

Parameters

NameTypeDescription
oldReserveFactorMantissauint256Previous reserve factor
newReserveFactorMantissauint256New reserve factor

ReservesAdded

Event emitted when the reserves are added

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

Parameters

NameTypeDescription
benefactoraddressAddress adding reserves
addAmountuint256Amount added
newTotalReservesuint256Total reserves after addition

ReservesReduced

Event emitted when the reserves are reduced

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

Parameters

NameTypeDescription
adminaddressAddress removing reserves
reduceAmountuint256Amount removed
newTotalReservesuint256Total reserves after reduction

NewBorrowRateMaxMantissa

Event emitted when the borrow max mantissa is updated

event NewBorrowRateMaxMantissa(uint256 oldVal, uint256 maxMantissa);

Parameters

NameTypeDescription
oldValuint256Previous max mantissa
maxMantissauint256New max mantissa

SameChainFlowStateUpdated

Event emitted when same chain flow state is enabled or disabled

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

Parameters

NameTypeDescription
senderaddressAddress updating the state
_oldStateboolPrevious state
_newStateboolNew state

ZkVerifierUpdated

Event emitted when zkVerifier is updated

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

Parameters

NameTypeDescription
oldVerifieraddressPrevious verifier
newVerifieraddressNew 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

Git Source

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

NameTypeDescription
repayAmountuint256Amount to repay or type(uint256).max

Returns

NameTypeDescription
repaidAmountuint256Actual repaid amount

repayBorrowBehalf

Repays a borrow on behalf of borrower

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

Parameters

NameTypeDescription
borroweraddressBorrower address
repayAmountuint256Amount to repay

Returns

NameTypeDescription
repaidAmountuint256Actual repaid amount

redeemUnderlying

Redeems underlying for given amount

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

Parameters

NameTypeDescription
redeemAmountuint256Amount to redeem

Returns

NameTypeDescription
redeemeduint256Amount of underlying redeemed

redeem

Redeems tokens

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

Parameters

NameTypeDescription
amountuint256Amount of tokens to redeem

Returns

NameTypeDescription
redeemeduint256Amount redeemed

balanceOfUnderlying

Returns underlying balance of sender

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

Parameters

NameTypeDescription
senderaddressAddress to query

Returns

NameTypeDescription
balanceuint256Underlying balance

underlying

Returns underlying asset address

function underlying() external view returns (address asset);

Returns

NameTypeDescription
assetaddressUnderlying token

balanceOf

Returns token balance of sender

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

Parameters

NameTypeDescription
senderaddressAddress to query

Returns

NameTypeDescription
tokenBalanceuint256Token balance

borrowBalanceStored

Returns stored borrow balance

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

Parameters

NameTypeDescription
senderaddressAddress to query

Returns

NameTypeDescription
borrowBalanceuint256Borrow balance

IMendiComptroller

Git Source

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

NameTypeDescription
accountaddressAccount address

Returns

NameTypeDescription
assetsIMendiMarket[]List of markets

Migrator

Git Source

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

NameTypeDescription
_operatoraddressAddress 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

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
positionsPosition[]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

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
marketsaddress[]Array of market addresses

_mintAll

Mints in v2 markets for all positions with collateral

function _mintAll(Position[] memory positions) private;

Parameters

NameTypeDescription
positionsPosition[]Positions to process

_borrowAll

Borrows in v2 markets for all positions requiring debt

function _borrowAll(Position[] memory positions) private;

Parameters

NameTypeDescription
positionsPosition[]Positions to process

_repayAll

Repays debts in v1 markets for all positions

function _repayAll(Position[] memory positions) private;

Parameters

NameTypeDescription
positionsPosition[]Positions to process

_withdrawAll

Withdraws collateral from v1 and transfers to v2 for all positions

function _withdrawAll(Position[] memory positions) private;

Parameters

NameTypeDescription
positionsPosition[]Positions to process

_collectMendiPositions

Collects all user positions from Mendi

function _collectMendiPositions(address user) private returns (Position[] memory);

Parameters

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
<none>Position[]Array of positions

_getMaldaMarket

Gets corresponding Malda market for a given underlying

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

Parameters

NameTypeDescription
underlyingaddressThe underlying token address

Returns

NameTypeDescription
<none>addressThe 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

Git Source

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

NameTypeDescription
owner_addressThe owner address

setGasFee

Sets the gas fee

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

Parameters

NameTypeDescription
dstChainIduint32The destination chain id
amountuint256The gas fee amount

Events

GasFeeUpdated

Event emitted when gas fee is updated

event GasFeeUpdated(uint32 indexed dstChainId, uint256 amount);

Parameters

NameTypeDescription
dstChainIduint32The destination chain ID
amountuint256The gas fee amount

ChainlinkOracle

Git Source

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

NameTypeDescription
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

NameTypeDescription
mTokenaddressThe mToken to get the price of

Returns

NameTypeDescription
<none>uint256price 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

NameTypeDescription
mTokenaddressThe mToken to get the underlying price of

Returns

NameTypeDescription
<none>uint256price 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

NameTypeDescription
symbolstringThe symbol to get price for

Returns

NameTypeDescription
<none>uint256answer The price
<none>uint256updatedAt 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

Git Source

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

NameTypeDescription
rolebytes32Role 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

NameTypeDescription
symbols_string[]Array of token symbols
configs_IDefaultAdapter.PriceConfig[]Array of price configs for symbols
roles_addressRoles contract address
stalenessPeriod_uint256Default staleness period

setStaleness

Sets a custom staleness period for a symbol

function setStaleness(string calldata symbol, uint256 val) external onlyRole(ROLES.GUARDIAN_ORACLE());

Parameters

NameTypeDescription
symbolstringSymbol to update
valuint256New 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

NameTypeDescription
symbolstringSymbol to configure
configIDefaultAdapter.PriceConfigPrice configuration

getUnderlyingPrice

Returns underlying price for an mToken

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

Parameters

NameTypeDescription
mTokenaddressAddress of the mToken

Returns

NameTypeDescription
<none>uint256Price 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

NameTypeDescription
mTokenaddressAddress of the mToken

Returns

NameTypeDescription
<none>uint256Price denominated in USD with 18 decimals

_getPriceUSD

Returns the USD price for a symbol

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

Parameters

NameTypeDescription
symbolstringToken symbol

Returns

NameTypeDescription
<none>uint256price 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

NameTypeDescription
symbolstringToken symbol
configIDefaultAdapter.PriceConfigPrice configuration for the symbol

Returns

NameTypeDescription
<none>uint256price Latest price from feed
<none>uint256decimals 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

NameTypeDescription
symbolstringToken symbol

Returns

NameTypeDescription
<none>uint256Staleness period in seconds

_onlyRole

Ensures caller has specific role

function _onlyRole(bytes32 role) internal view;

Parameters

NameTypeDescription
rolebytes32Role identifier to check

Events

ConfigSet

Emitted when a configuration is set for a symbol

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

Parameters

NameTypeDescription
symbolstringSymbol being configured
configIDefaultAdapter.PriceConfigPrice configuration applied

StalenessUpdated

Emitted when staleness is updated for a symbol

event StalenessUpdated(string symbol, uint256 val);

Parameters

NameTypeDescription
symbolstringSymbol being updated
valuint256New 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

Git Source

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

NameTypeDescription
rolebytes32Role identifier to check

constructor

Initializes the oracle with configs, roles, and staleness

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

Parameters

NameTypeDescription
symbols_string[]Symbols being configured
configs_PriceConfig[]Price configs for symbols
roles_addressRoles contract address
stalenessPeriod_uint256Default staleness period

setStaleness

Sets a custom staleness for a symbol

function setStaleness(string calldata symbol, uint256 val) external onlyRole(ROLES.GUARDIAN_ORACLE());

Parameters

NameTypeDescription
symbolstringSymbol to update
valuint256New staleness value

setConfig

Sets price configuration for a symbol

function setConfig(string calldata symbol, PriceConfig calldata config) external onlyRole(ROLES.GUARDIAN_ORACLE());

Parameters

NameTypeDescription
symbolstringSymbol to configure
configPriceConfigPrice configuration

setMaxPriceDelta

Sets maximum allowed price delta

function setMaxPriceDelta(uint256 _delta) external onlyRole(ROLES.GUARDIAN_ORACLE());

Parameters

NameTypeDescription
_deltauint256New 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

NameTypeDescription
_deltauint256New delta in basis points
_symbolstringSymbol to update

getPrice

Returns price for an mToken

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

Parameters

NameTypeDescription
mTokenaddressAddress of the mToken

Returns

NameTypeDescription
<none>uint256Price denominated in USD with 18 decimals

getUnderlyingPrice

Returns underlying price for an mToken

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

Parameters

NameTypeDescription
mTokenaddressAddress of the mToken

Returns

NameTypeDescription
<none>uint256Price denominated in USD with 18 decimals adjusted for underlying decimals

_onlyRole

Ensures caller has specific role

function _onlyRole(bytes32 role) internal view;

Parameters

NameTypeDescription
rolebytes32Role identifier to check

_getPriceUSD

Returns USD price for a symbol using dual feeds

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

Parameters

NameTypeDescription
symbolstringToken symbol

Returns

NameTypeDescription
<none>uint256USD 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

NameTypeDescription
symbolstringToken symbol

Returns

NameTypeDescription
priceuint256Price scaled to 18 decimals
lastUpdateuint256Timestamp of last update

_getChainlinkPrice

Retrieves price and last update from secondary feed

function _getChainlinkPrice(string memory symbol) internal view returns (uint256 price, uint256 lastUpdate);

Parameters

NameTypeDescription
symbolstringToken symbol

Returns

NameTypeDescription
priceuint256Price scaled to 18 decimals
lastUpdateuint256Timestamp of last update

_isFresh

Checks if price data is fresh

function _isFresh(uint256 updatedAt, uint256 staleness) internal view returns (bool);

Parameters

NameTypeDescription
updatedAtuint256Timestamp of last update
stalenessuint256Allowed staleness threshold

Returns

NameTypeDescription
<none>boolTrue if data is within staleness window

_getStaleness

Returns staleness for a symbol or default

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

Parameters

NameTypeDescription
symbolstringToken symbol

Returns

NameTypeDescription
<none>uint256Staleness period in seconds

_absDiff

Absolute difference between two int256 values

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

Parameters

NameTypeDescription
aint256First value
bint256Second value

Returns

NameTypeDescription
<none>uint256Absolute difference as uint256

Events

ConfigSet

Emitted when a config is set for a symbol

event ConfigSet(string symbol, PriceConfig config);

Parameters

NameTypeDescription
symbolstringSymbol being configured
configPriceConfigPrice config stored

StalenessUpdated

Emitted when staleness is updated for a symbol

event StalenessUpdated(string symbol, uint256 val);

Parameters

NameTypeDescription
symbolstringSymbol being updated
valuint256New staleness period

PriceDeltaUpdated

Emitted when global price delta is updated

event PriceDeltaUpdated(uint256 oldVal, uint256 newVal);

Parameters

NameTypeDescription
oldValuint256Previous delta value
newValuint256New delta value

PriceSymbolDeltaUpdated

Emitted when symbol price delta is updated

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

Parameters

NameTypeDescription
oldValuint256Previous delta
newValuint256New delta
symbolstringSymbol 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_ChainlinkStalePrice

Error thrown when secondary feed price is stale

error MixedPriceOracle_ChainlinkStalePrice();

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 chainlinkFeed;
    string api3ToSymbol;
    string chainlinkToSymbol;
    uint256 underlyingDecimals;
}

Contents

Pauser

Git Source

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

NameTypeDescription
_rolesaddressAddress of the roles contract
_operatoraddressAddress of the operator contract
owner_addressOwner address of the pauser contract

addPausableMarket

Add pausable contract

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

Parameters

NameTypeDescription
_contractaddressthe pausable contract
_contractTypePausableTypethe pausable contract type

removePausableMarket

Removes pausable contract

function removePausableMarket(address _contract) external onlyOwner;

Parameters

NameTypeDescription
_contractaddressthe pausable contract

emergencyPauseMarket

Pauses all operations for a market

function emergencyPauseMarket(address _market) external;

Parameters

NameTypeDescription
_marketaddressthe mToken address

emergencyPauseMarketFor

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

NameTypeDescription
_marketaddressThe market to pause

_pauseMarketOperation

Pauses a specific market operation type

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

Parameters

NameTypeDescription
_marketaddressThe market to pause
_pauseTypeImTokenOperationTypes.OperationTypeThe operation type to pause

_pause

Performs pause logic depending on contract type

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

Parameters

NameTypeDescription
_marketaddressThe market address to pause
_pauseTypeImTokenOperationTypes.OperationTypeThe operation type to pause

_findIndex

Finds the index of a market within the pausableContracts array

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

Parameters

NameTypeDescription
_addressaddressThe market address to search for

Returns

NameTypeDescription
<none>uint256index The index of the market

Contents

Contents

Contents

CCTPHelper

Git Source

Title: CCTPHelper

Author: Malda Protocol

Helper for building/sending/receiving CCTP v2 messages and encoding/decoding hook payloads.

State Variables

TOKEN_MESSENGER

Circle TokenMessenger (v2) used to burn tokens and attach hook data.

address public immutable TOKEN_MESSENGER

MESSAGE_TRANSMITTER

Circle MessageTransmitter (v2) used to validate and receive messages with attestations.

address public immutable MESSAGE_TRANSMITTER

acceptedTokens

Token allowlist for burns via CCTP.

mapping(address token => bool isAccepted) public acceptedTokens

Functions

constructor

Constructor for the CCTPHelper contract.

constructor(address _tokenMessenger, address _messageTransmitter) ;

Parameters

NameTypeDescription
_tokenMessengeraddressAddress of the TokenMessenger contract.
_messageTransmitteraddressAddress of the MessageTransmitter contract.

createAndBurn

Burns tokens via CCTP v2 and returns the decoded message struct plus its encoded representation.

function createAndBurn(
    address _token,
    uint256 _amount,
    uint32 _dstDomain,
    bytes32 _receiver,
    bytes memory _payload,
    uint32 _srcDomain
) internal returns (CCTPMessage memory msgData, bytes memory encoded);

Parameters

NameTypeDescription
_tokenaddressToken to burn.
_amountuint256Amount to burn.
_dstDomainuint32Destination CCTP domain.
_receiverbytes32Receiver bytes32 (typically the bridge address encoded).
_payloadbytesApp payload to attach as hook data.
_srcDomainuint32Source CCTP domain.

Returns

NameTypeDescription
msgDataCCTPMessageParsed message struct (nonce is 0 for v2).
encodedbytesPacked encoding of msgData produced by _encodeMsg.

handleDestinationMsg

Validates a CCTP message+attestation via Circle and decodes the embedded hook payload into a CCTPMessage.

function handleDestinationMsg(bytes calldata cctpMessage, bytes calldata attestation)
    internal
    returns (CCTPMessage memory msgData);

Parameters

NameTypeDescription
cctpMessagebytesRaw CCTP message bytes.
attestationbytesCircle attestation proving message validity.

Returns

NameTypeDescription
msgDataCCTPMessageDecoded app-level message extracted from the hook payload.

_toBytes32

Converts an address to a left-padded bytes32 representation.

function _toBytes32(address addr) internal pure returns (bytes32);

Parameters

NameTypeDescription
addraddressAddress to convert.

Returns

NameTypeDescription
<none>bytes32Encoded bytes32.

_burnSrc

Burns tokens via CCTP v2 and returns the nonce.

function _burnSrc(address _token, uint256 _amount, uint32 _dstDomain, bytes32 _receiver, bytes memory _payload)
    private
    returns (uint64 nonce);

Parameters

NameTypeDescription
_tokenaddressToken to burn.
_amountuint256Amount to burn.
_dstDomainuint32Destination CCTP domain.
_receiverbytes32Receiver bytes32 (typically the bridge address encoded).
_payloadbytesApp payload to attach as hook data.

Returns

NameTypeDescription
nonceuint64Nonce of the burn.

_encodeMsg

Encodes a CCTPMessage into a compact, packed byte format. Layout (all fields big-endian where applicable):

  • [ 0 .. 0] : uint8 payloadId (fixed = 1)
  • [ 1 .. 32] : bytes32 token (ERC20 address left-padded to 32 bytes)
  • [ 33 .. 64] : uint256 amount
  • [ 65 .. 68] : uint32 srcChain (CCTP domain / chain id)
  • [ 69 .. 72] : uint32 dstChain
  • [ 73 .. 80] : uint64 nonce (0 for CCTP v2; kept for compatibility)
  • [ 81 .. 112] : bytes32 from (sender address left-padded)
  • [113 .. 144] : bytes32 receiver (receiver address or arbitrary 32 bytes)
  • [145 .. 146] : uint16 payloadLen (length of payload below)
  • [147 .. end] : bytes payload (opaque app-level payload) Minimum length with empty payload is therefore 147 bytes.

Encodes a CCTPMessage into a compact, packed byte format.

function _encodeMsg(CCTPMessage memory message) private pure returns (bytes memory);

Parameters

NameTypeDescription
messageCCTPMessageCCTPMessage to encode.

Returns

NameTypeDescription
<none>bytesencoded Encoded packed representation of the message.

_decodeMsg

Decodes bytes produced by _encodeMsg back into a CCTPMessage. Expects exactly the layout documented above:

  • Reverts with CCTPHelper_MsgTooShort if the buffer is shorter than the fixed header (147 bytes).
  • Reverts with CCTPHelper_PayloadMismatch if payloadId != 1.
  • Reverts with CCTPHelper_LengthMismatch if the trailing bytes length does not match the embedded payloadLen. Numeric fields are read as big-endian from the high bits of a 32-byte word:
  • uint32 values are taken from the highest 4 bytes of the word (shr(224, ...)).
  • uint64 values are taken from the highest 8 bytes of the word (shr(192, ...)).
  • uint16 values are taken from the highest 2 bytes of the word (shr(240, ...)). The payload bytes are copied verbatim into a new bytes array.

Decodes bytes produced by _encodeMsg back into a CCTPMessage.

function _decodeMsg(bytes memory encoded) private pure returns (CCTPMessage memory message);

Parameters

NameTypeDescription
encodedbytesEncoded packed representation of the message.

Returns

NameTypeDescription
messageCCTPMessageDecoded CCTPMessage.

Events

BurnInitiated

Emitted after a burn is initiated via TokenMessenger.

event BurnInitiated(
    address indexed token,
    uint256 amount,
    uint32 dstDomain,
    bytes32 indexed recipient,
    uint64 indexed nonce,
    bytes payload
);

Parameters

NameTypeDescription
tokenaddressThe ERC20 token burned.
amountuint256The amount burned.
dstDomainuint32The destination CCTP domain.
recipientbytes32The destination recipient (bytes32).
nonceuint64Always 0 for CCTP v2 (kept for compatibility).
payloadbytesHook payload passed to Circle.

MessageCreated

Emitted when an app-level message payload is constructed and encoded.

event MessageCreated(
    bytes32 indexed token,
    uint256 amount,
    uint32 indexed srcDomain,
    uint32 indexed dstDomain,
    uint64 nonce,
    bytes32 from,
    bytes32 receiver,
    bytes payload,
    bytes encodedMessage
);

Parameters

NameTypeDescription
tokenbytes32Token address (bytes32 encoded).
amountuint256Amount burned.
srcDomainuint32Source CCTP domain.
dstDomainuint32Destination CCTP domain.
nonceuint64Always 0 for CCTP v2 (kept for compatibility).
frombytes32Sender (bytes32 encoded).
receiverbytes32Receiver (bytes32).
payloadbytesApp payload.
encodedMessagebytesEncoded packed representation produced by _encodeMsg.

MessageReceived

Emitted after a message is received/validated by Circle and decoded into the app payload.

event MessageReceived(
    uint64 indexed nonce,
    uint32 indexed srcDomain,
    uint32 indexed dstDomain,
    uint256 amount,
    bytes32 receiver,
    bytes payload
);

Parameters

NameTypeDescription
nonceuint64Always 0 for CCTP v2 (kept for compatibility).
srcDomainuint32Source CCTP domain.
dstDomainuint32Destination CCTP domain.
amountuint256Amount received.
receiverbytes32Receiver (bytes32).
payloadbytesApp payload.

Errors

CCTPHelper_AmountZero

error CCTPHelper_AmountZero();

CCTPHelper_AddressZero

error CCTPHelper_AddressZero();

CCTPHelper_TokenNotAccepted

error CCTPHelper_TokenNotAccepted();

CCTPHelper_ReceiveFailed

error CCTPHelper_ReceiveFailed();

CCTPHelper_LengthMismatch

error CCTPHelper_LengthMismatch();

CCTPHelper_PayloadMismatch

error CCTPHelper_PayloadMismatch();

CCTPHelper_MsgTooShort

error CCTPHelper_MsgTooShort();

Structs

CCTPMessage

Struct used to encode and decode the app-level hook payload carried by CCTP v2.

struct CCTPMessage {
    bytes32 token; // ERC20 token address left-padded to 32 bytes
    uint256 amount;
    uint32 srcChain; // CCTP domain on source
    uint32 dstChain; // CCTP domain on destination
    uint64 nonce; // always 0 for v2; kept for compatibility
    bytes32 from; // msg.sender on source (left-padded)
    bytes32 receiver; // receiver/caller bytes32
    bytes payload; // opaque app payload
}

Contents

BaseOftMessageExecutor

Git Source

Inherits: IOftMessageExecutor

Title: BaseOftMessageExecutor

Author: Malda Protocol

Base implementation for OFT message executors used via delegatecall by bridges.

Functions

processUncomposed

Processes stored/uncomposed messages for a market by falling back to underlying.

function processUncomposed(address market, address underlying, address bridgeContract)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
marketaddressThe market address.
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for OFT operations.

executeCompose

Executes a compose step for a market by falling back to underlying.

function executeCompose(address market, address underlying, address bridgeContract)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
marketaddressThe market address.
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for OFT operations.

_pullFromRebalancer

Pulls tokens from the rebalancer.

function _pullFromRebalancer(address underlying, uint256 amount, address rebalancer) internal;

Parameters

NameTypeDescription
underlyingaddressThe underlying token address.
amountuint256The amount of tokens to pull.
rebalanceraddressThe rebalancer address.

_approve

Approves tokens to a spender.

function _approve(address token, address spender, uint256 amount) internal;

Parameters

NameTypeDescription
tokenaddressThe token address.
spenderaddressThe spender address.
amountuint256The amount of tokens to approve.

_sendOFT

Sends tokens via OFT.

function _sendOFT(address oft, SendParam calldata params, MessagingFee calldata fees, address refundAddress)
    internal
    returns (MessagingReceipt memory receipt);

Parameters

NameTypeDescription
oftaddressThe OFT address.
paramsSendParamThe send parameters.
feesMessagingFeeThe messaging fees.
refundAddressaddressThe refund address.

Returns

NameTypeDescription
receiptMessagingReceiptThe messaging receipt.

_fallbackToUnderlying

Falls back to underlying if the bridge contract is not the underlying.

function _fallbackToUnderlying(address market, address underlying, address bridgeContract) internal;

Parameters

NameTypeDescription
marketaddressThe market address.
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for OFT operations.

_verifyMinted

Verifies the minted tokens.

function _verifyMinted(address oft, uint256 required) internal view;

Parameters

NameTypeDescription
oftaddressThe OFT address.
requireduint256The required amount of tokens.

Errors

Executor_NoOft

error Executor_NoOft();

Executor_AmountMismatch

error Executor_AmountMismatch();

Executor_WrongUnderlying

error Executor_WrongUnderlying();

Executor_NotRebalancer

error Executor_NotRebalancer();

rsEthOftMessageExecutor

Git Source

Inherits: BaseOftMessageExecutor

Title: rsEthOftMessageExecutor

Author: Malda Protocol

OFT message executor for rsETH-like wrapper OFTs where the underlying may wrap/unwrap into an inner token.

Functions

executeSend

Pulls tokens from the rebalancer, unwraps if needed, then sends via OFT.

function executeSend(
    address underlying,
    address bridgeContract,
    SendParam calldata params,
    MessagingFee calldata fees,
    address rebalancer,
    address refundAddress
) external payable override returns (MessagingReceipt memory);

Parameters

NameTypeDescription
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for the OFT send (may differ from underlying).
paramsSendParamLayerZero send parameters.
feesMessagingFeeLayerZero messaging fees.
rebalanceraddressThe rebalancer address providing the funds.
refundAddressaddressAddress that receives any excess native fee refund.

Returns

NameTypeDescription
<none>MessagingReceiptMessagingReceipt LayerZero receipt containing the message GUID.

Errors

Executor_DifferentInnerToken

Thrown when the bridge contract is not an allowed inner token for the wrapper.

error Executor_DifferentInnerToken();

weEthOftMessageExecutor

Git Source

Inherits: BaseOftMessageExecutor

Title: weEthOftMessageExecutor

Author: Malda Protocol

OFT message executor for weETH-style OFTs where the bridge contract exposes an inner token().

Functions

executeSend

Executes a send message for weETH

function executeSend(
    address underlying,
    address bridgeContract,
    SendParam calldata params,
    MessagingFee calldata fees,
    address rebalancer,
    address refundAddress
) external payable override returns (MessagingReceipt memory);

Parameters

NameTypeDescription
underlyingaddressThe underlying token address.
bridgeContractaddressThe bridge contract used for the OFT send (may differ from underlying).
paramsSendParamLayerZero send parameters.
feesMessagingFeeLayerZero messaging fees.
rebalanceraddressThe rebalancer address providing the funds.
refundAddressaddressAddress that receives any excess native fee refund.

Returns

NameTypeDescription
<none>MessagingReceiptMessagingReceipt LayerZero receipt containing the message GUID.

Errors

Executor_DifferentInnerToken

Thrown when the OFT's inner token() does not match the provided underlying.

error Executor_DifferentInnerToken();

AccrossBridge

Git Source

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

NameTypeDescription
_rolesaddressAddress of the roles contract
_spokePooladdressAddress of the Across spoke pool
_rebalanceraddressAddress 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

NameTypeDescription
_dstIduint32The destination chain ID
_relayeraddressThe relayer address to update
statusboolWhether 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

NameTypeDescription
tokenSentaddressthe token address received
amountuint256the token amount
<none>address
messagebytesthe 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

NameTypeDescription
_extractedAmountuint256extracted amount for rebalancing
_marketaddressdestination address
_dstChainIduint32destination chain id
_tokenaddressthe token to rebalance
_messagebytesoperation 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

NameTypeDescription
dstChainuint32The destination chain ID
relayeraddressThe relayer address

Returns

NameTypeDescription
<none>boolisWhitelisted 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

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

Returns

NameTypeDescription
<none>uint256fee 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

NameTypeDescription
_messagebytesEncoded Across message
_tokenaddressToken being transferred
_dstChainIduint32Destination chain ID
_marketaddressMarket address encoded in the message

_decodeMessage

Decodes the Across message payload

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

Parameters

NameTypeDescription
_messagebytesEncoded message data

Returns

NameTypeDescription
messageDataDecodedMessageThe decoded message struct

Events

Rebalanced

Emitted when funds are rebalanced to a market

event Rebalanced(address indexed market, uint256 amount);

Parameters

NameTypeDescription
marketaddressThe market receiving funds
amountuint256The amount rebalanced

WhitelistedRelayerStatusUpdated

Emitted when relayer whitelist status is updated

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

Parameters

NameTypeDescription
senderaddressThe caller updating whitelist
dstIduint32The destination chain ID
delegateaddressThe relayer address
statusboolThe 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

Git Source

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

NameTypeDescription
_rolesaddressRoles 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();

CCTPBridge

Git Source

Inherits: BaseBridge, CCTPHelper, IBridge, ReentrancyGuard

Title: CCTPBridge

Author: Malda Protocol

Cross-chain bridge that uses Circle CCTP v2

State Variables

REBALANCER

The Rebalancer contract allowed to initiate bridging actions.

address public immutable REBALANCER

chainIdToDomain

Maps EVM chainId -> CCTP domain id.

mapping(uint32 chainId => uint32 cctpDomain) public chainIdToDomain

domainSet

Tracks whether a domain mapping exists for a given EVM chainId.

mapping(uint32 chainId => bool isSet) public domainSet

Functions

constructor

Constructor for the CCTPBridge contract.

constructor(address _roles, address _tokenMessenger, address _messageTransmitter, address _rebalancer)
    BaseBridge(_roles)
    CCTPHelper(_tokenMessenger, _messageTransmitter);

Parameters

NameTypeDescription
_rolesaddressAddress of the Roles contract.
_tokenMessengeraddressAddress of the TokenMessenger contract.
_messageTransmitteraddressAddress of the MessageTransmitter contract.
_rebalanceraddressAddress of the Rebalancer contract.

setDomainMapping

Sets the CCTP domain id for a given EVM chainId.

function setDomainMapping(uint32 chainId, uint32 domain) external onlyBridgeConfigurator;

Parameters

NameTypeDescription
chainIduint32The EVM chainId to set.
domainuint32The corresponding CCTP domain id.

setAcceptedToken

Enables or disables a token for use with CCTP burns.

function setAcceptedToken(address token, bool allowed) external onlyBridgeConfigurator;

Parameters

NameTypeDescription
tokenaddressThe token address.
allowedboolTrue to enable, false to disable.

sendMsg

Burns tokens and creates a CCTP message for the destination chain.

function sendMsg(
    uint256 _extractedAmount,
    address _market,
    uint32 _dstChainId,
    address _token,
    bytes calldata _unused1,
    bytes calldata _unused2
) external payable override onlyRebalancer;

Parameters

NameTypeDescription
_extractedAmountuint256Amount to burn.
_marketaddressDestination market address (encoded into the CCTP hook payload).
_dstChainIduint32Destination EVM chainId.
_tokenaddressToken to burn (e.g., USDC).
_unused1bytesUnused parameter kept for IBridge compatibility.
_unused2bytesUnused parameter kept for IBridge compatibility.

handleCCTPMessage

Receives a CCTP message+attestation and forwards received tokens to the encoded destination market.

function handleCCTPMessage(bytes calldata cctpMessage, bytes calldata attestation) external nonReentrant;

Parameters

NameTypeDescription
cctpMessagebytesRaw CCTP message bytes.
attestationbytesCircle attestation proving message validity.

getFee

computes fee for bridge operation

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

Parameters

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

Returns

NameTypeDescription
<none>uint256fee Computed bridge fee

Events

Rebalanced

Emitted when bridged funds are forwarded to a destination market.

event Rebalanced(address indexed market, uint256 amount);

Parameters

NameTypeDescription
marketaddressThe destination market that received the funds.
amountuint256The amount of tokens forwarded to the market.

DomainMappingUpdated

Emitted when a chainId -> CCTP domain mapping is updated.

event DomainMappingUpdated(uint32 indexed chainId, uint32 indexed domain);

Parameters

NameTypeDescription
chainIduint32The EVM chainId.
domainuint32The CCTP domain id.

TokenAccepted

Emitted when a token is enabled or disabled for CCTP burns.

event TokenAccepted(address indexed token, bool status);

Parameters

NameTypeDescription
tokenaddressThe token address.
statusboolTrue if enabled, false if disabled.

Errors

CCTPBridge_AddressNotValid

error CCTPBridge_AddressNotValid();

CCTPBridge_InvalidReceiver

error CCTPBridge_InvalidReceiver();

CCTPBridge_TokenMismatch

error CCTPBridge_TokenMismatch();

CCTPBridge_NotImplemented

error CCTPBridge_NotImplemented();

CCTPBridge_DomainNotSet

error CCTPBridge_DomainNotSet();

EverclearBridge

Git Source

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

NameTypeDescription
_rolesaddressRoles contract address
_feeAdapteraddressEverclear 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

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

getFee

computes fee for bridge operation

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

Parameters

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

Returns

NameTypeDescription
<none>uint256fee Computed bridge fee

_decodeIntent

Decodes an intent message returned by the Everclear intents API into structured parameters.

  • The input message is the raw ABI-encoded calldata of a FeeAdapter.newIntent call.
  • The first 4 bytes are the function selector, which are skipped.
  • The remaining bytes encode the primary intent parameters followed by FeeParams.
  • Because FeeParams is a dynamic struct appended at the end, its data must be located by reading its offset and decoding separately. Layout of FeeAdapter.newIntent calldata 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

NameTypeDescription
messagebytesABI-encoded calldata for FeeAdapter.newIntent.

Returns

NameTypeDescription
<none>IntentParamsDecoded IntentParams struct with both core parameters and nested FeeParams.

_extractFeeParams

Extracts the nested FeeParams struct from ABI-encoded intentData.

  • FeeParams is the 9th parameter of FeeAdapter.newIntent and therefore stored as a pointer at offset 0x100.
  • 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 FeeParams struct 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 sig field is dynamic, so we read its offset (at +0x40) relative to the FeeParams base, 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

NameTypeDescription
intentDatabytesABI-encoded calldata without selector, containing intent arguments.

Returns

NameTypeDescription
feeuint256The fee value.
deadlineuint256The signature deadline.
sigbytesThe 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

NameTypeDescription
dstChainIduint256Destination chain ID
marketaddressMarket address
amountLDuint256Amount in local decimals
idbytes32Intent identifier

RebalancingReturnedToMarket

Emitted when excess rebalancing funds are returned to the market

event RebalancingReturnedToMarket(address indexed market, uint256 toReturn, uint256 extracted);

Parameters

NameTypeDescription
marketaddressMarket address
toReturnuint256Amount returned
extracteduint256Amount 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;
}

EverclearBridgeV2

Git Source

Inherits: BaseBridge, IBridge

Title: Everclear V2 bridge implementation

Author: Malda Protocol

Cross-chain bridge using Everclear V2 protocol for intent-based transfers

State Variables

everclearFeeAdapter

Everclear V2 fee adapter contract

IFeeAdapterV2 public everclearFeeAdapter

Functions

constructor

Initializes the Everclear V2 bridge

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

Parameters

NameTypeDescription
_rolesaddressRoles contract address
_feeAdapteraddressEverclear V2 fee adapter address

setEverclearFeeAdapter

Sets the Everclear V2 fee adapter contract

function setEverclearFeeAdapter(address _feeAdapter) external onlyBridgeConfigurator;

Parameters

NameTypeDescription
_feeAdapteraddressNew Everclear V2 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

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

getFee

computes fee for bridge operation

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

Parameters

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

Returns

NameTypeDescription
<none>uint256fee Computed bridge fee

_decodeIntent

Decodes an intent message returned by the Everclear intents API into structured parameters.

  • The input message is the raw ABI-encoded calldata of a FeeAdapterV2.newIntent call.
  • The first 4 bytes are the function selector, which are skipped.
  • The remaining bytes encode the primary intent parameters followed by FeeParams.
  • Because FeeParams is a dynamic struct appended at the end, its data must be located by reading its offset and decoding separately. Layout of FeeAdapterV2.newIntent calldata after the selector:
destinations (uint32[])   offset 0x00
receiver (bytes32)        offset 0x20
inputAsset (address)      offset 0x40
outputAsset (bytes32)     offset 0x60
amount (uint256)          offset 0x80
amountOutMin (uint256)    offset 0xa0
ttl (uint48)              offset 0xc0
data (bytes)              offset 0xe0
feeParams (FeeParams)     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

NameTypeDescription
messagebytesABI-encoded calldata for FeeAdapterV2.newIntent.

Returns

NameTypeDescription
<none>IntentParamsDecoded IntentParams struct with both core parameters and nested FeeParams.

_extractFeeParams

Extracts the nested FeeParams struct from ABI-encoded intentData.

  • FeeParams is the 9th parameter of FeeAdapterV2.newIntent and therefore stored as a pointer at offset 0x100.
  • 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 FeeParams struct relative to the start of intentData.
  • Within FeeParams, the layout is:
fee      (uint256) +0x00
deadline (uint256) +0x20
sig      (bytes)   +0x40 (stored as offset → length → data)
  • The sig field is dynamic, so we read its offset (at +0x40) relative to the FeeParams base, 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

NameTypeDescription
intentDatabytesABI-encoded calldata without selector, containing intent arguments.

Returns

NameTypeDescription
feeuint256The fee value.
deadlineuint256The signature deadline.
sigbytesThe validator/relayer signature.

Events

MsgSent

Emitted when a message is sent via Everclear V2

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

Parameters

NameTypeDescription
dstChainIduint256Destination chain ID
marketaddressDestination market address
amountLDuint256Amount in local decimals
idbytes32Intent identifier

RebalancingReturnedToMarket

Emitted when excess rebalancing funds are returned to the market

event RebalancingReturnedToMarket(address indexed market, uint256 toReturn, uint256 extracted);

Parameters

NameTypeDescription
marketaddressDestination market address
toReturnuint256Amount returned
extracteduint256Amount originally extracted

EverclearFeeAdapterUpdated

Emitted when the Everclear V2 fee adapter is updated

event EverclearFeeAdapterUpdated(address indexed oldAdapter, address indexed newAdapter);

Parameters

NameTypeDescription
oldAdapteraddressOld Everclear V2 fee adapter address
newAdapteraddressNew Everclear V2 fee adapter address

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_MaxSlippageExceeded

Error thrown when maximum slippage is exceeded

error Everclear_MaxSlippageExceeded();

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

Parameters for creating a new intent with fees

Will be used for initiating a call to https://github.com/everclearorg/monorepo/blob/dev/packages/contracts/src/interfaces/intent/IFeeAdapterV2.sol#L129

struct IntentParams {
    uint32[] destinations;
    bytes32 receiver;
    address inputAsset;
    bytes32 outputAsset;
    uint256 amount;
    uint256 amountOutMin;
    uint48 ttl;
    bytes data;
    IFeeAdapterV2.FeeParams feeParams;
}

LZUnifiedBridge

Git Source

Inherits: BaseBridge, IBridge

Title: LZUnifiedBridge

Author: Malda Protocol

LayerZero v2 unified bridge used by the Rebalancer to send assets cross-chain via OFT-compatible tokens.

State Variables

ENDPOINT

LayerZero endpoint contract allowed to call lzCompose().

address public immutable ENDPOINT

bridgeContracts

Maps underlying token => bridge contract (OFT). If not set, defaults to underlying itself.

mapping(address underlying => address bridgeContract) public bridgeContracts

oftExecutors

Maps underlying token => executor contract used via delegatecall for send/compose flows.

mapping(address underlying => address executor) public oftExecutors

Functions

constructor

Creates the unified LayerZero bridge.

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

Parameters

NameTypeDescription
_rolesaddressRoles contract used by BaseBridge.
_endpointaddressLayerZero endpoint allowed to call lzCompose().

setBridgeContract

Sets the OFT bridge contract for an underlying token.

function setBridgeContract(address underlying, address bridgeContract) external onlyBridgeConfigurator;

Parameters

NameTypeDescription
underlyingaddressUnderlying token.
bridgeContractaddressOFT/bridge contract to use for that underlying.

setOftExecutorContract

Sets the executor contract for an underlying token.

function setOftExecutorContract(address underlying, address bridgeContract) external onlyBridgeConfigurator;

Parameters

NameTypeDescription
underlyingaddressUnderlying token.
bridgeContractaddressExecutor contract (kept as name for backward-compat with existing calls/logs).

sendMsg

Sends a message + tokens via OFT, delegating to an executor per underlying.

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

Parameters

NameTypeDescription
_extractedAmountuint256Amount extracted by the rebalancer.
_marketaddressMarket address expected inside _message.
_dstChainIduint32Destination chain id (eid).
_tokenaddressUnderlying token (must match market.underlying()).
_messagebytesABI-encoded (market, amountLD, minAmountLD, extraOptions).
_extraDatabytesABI-encoded refund address.

lzCompose

LayerZero compose callback. Delegates compose execution to the configured executor.

function lzCompose(address from, bytes32 guid, bytes calldata message, address executor, bytes calldata extraData)
    external
    payable;

Parameters

NameTypeDescription
fromaddressExpected to be the bridge contract (OFT) for the decoded underlying.
guidbytes32Unused.
messagebytesABI-encoded (market).
executoraddressUnused.
extraDatabytesUnused.

processUncomposedMessages

Processes any stored/uncomposed messages for a market (via executor).

function processUncomposedMessages(address _market) external payable onlyBridgeConfigurator;

Parameters

NameTypeDescription
_marketaddressMarket address.

getFee

Quotes the native fee required to send the message.

function getFee(uint32 _dstChainId, bytes calldata _message, bytes calldata _extraData)
    external
    view
    returns (uint256 nativeFee);

Parameters

NameTypeDescription
_dstChainIduint32Destination chain id (eid).
_messagebytesABI-encoded (market, amountLD, minAmountLD, extraOptions).
_extraDatabytesUnused.

Returns

NameTypeDescription
nativeFeeuint256Native fee quoted by the OFT.

_delegateExecuteSend

Delegates executeSend to the configured executor and decodes the MessagingReceipt.

function _delegateExecuteSend(
    address underlying,
    address bridgeContract,
    SendParam memory params,
    MessagingFee memory fees,
    address rebalancer,
    address refundAddress
) private returns (MessagingReceipt memory r);

Parameters

NameTypeDescription
underlyingaddressUnderlying token.
bridgeContractaddressOFT/bridge contract used for the send.
paramsSendParamLayerZero SendParam.
feesMessagingFeeLayerZero MessagingFee.
rebalanceraddressCaller (expected rebalancer).
refundAddressaddressRefund address for any extra native fee.

Returns

NameTypeDescription
rMessagingReceiptMessagingReceipt returned by the executor.

_getFee

Internal helper to quote fees and build SendParam.

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

Parameters

NameTypeDescription
dstEiduint32Destination chain id (eid).
_messagebytesABI-encoded (market, amountLD, minAmountLD, extraOptions).

Returns

NameTypeDescription
feesMessagingFeeLayerZero messaging fees.
lzSendParamsSendParamLayerZero send parameters.

Events

MsgSent

Emitted after a message is sent via LayerZero.

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

Parameters

NameTypeDescription
dstChainIduint32Destination chain id (eid).
marketaddressMarket address encoded in compose payload.
amountLDuint256Amount sent (local decimals).
minAmountLDuint256Minimum amount expected on destination (local decimals).
guidbytes32LayerZero message GUID.

BridgeContractSet

Emitted when a bridge contract is configured for an underlying.

event BridgeContractSet(address indexed underlying, address indexed bridgeContract);

Parameters

NameTypeDescription
underlyingaddressUnderlying token address.
bridgeContractaddressBridge contract (OFT) used for that underlying.

OftExecutorSet

Emitted when an OFT executor is configured for an underlying.

event OftExecutorSet(address indexed underlying, address indexed executor);

Parameters

NameTypeDescription
underlyingaddressUnderlying token address.
executoraddressExecutor contract address.

Errors

LZBridge_NotEnoughFees

error LZBridge_NotEnoughFees();

LZBridge_ChainNotRegistered

error LZBridge_ChainNotRegistered();

LZBridge_DestinationMismatch

error LZBridge_DestinationMismatch();

LZBridge_DifferentInnerToken

error LZBridge_DifferentInnerToken();

LZBridge_NoOft

error LZBridge_NoOft();

LZBridge_TokenMismatch

error LZBridge_TokenMismatch();

LZBridge_ExecutorNotSet

error LZBridge_ExecutorNotSet();

LZBridge_ExecutorNoCode

error LZBridge_ExecutorNoCode();

LZBridge_OnlyEndpoint

error LZBridge_OnlyEndpoint();

LZBridge_BadFrom

error LZBridge_BadFrom();

LZBridge_RefunderNotValid

error LZBridge_RefunderNotValid();

LZBridge_EndpointZero

error LZBridge_EndpointZero();

Structs

SendMsgLocalVars

Local vars used to avoid stack-too-deep in sendMsg().

struct SendMsgLocalVars {
    address market;
    address underlying;
    address bridgeContract;
    MessagingFee fees;
    SendParam sendParam;
}

Rebalancer

Git Source

Inherits: IRebalancer, HypernativeFirewallProtected

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 dstChainId => mapping(uint256 msgNonce => Msg message)) public logs

whitelistedBridges

Bridge whitelist status.

mapping(address bridge => bool status) public whitelistedBridges

allowedTokensPerBridge

Allowed tokens per bridge.

mapping(address bridge => mapping(address token => bool status)) public allowedTokensPerBridge

whitelistedDestinations

Destination chain whitelist status.

mapping(uint32 dstChainId => bool status) public whitelistedDestinations

allowedList

Markets allowed for rebalancing.

mapping(address market => bool status) 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 limit)) public maxTransferSizes

minTransferSizes

Per-chain token minimum transfer size.

mapping(uint32 dstChainId => mapping(address token => uint256 limit)) public minTransferSizes

currentTransferSize

Rolling transfer info for size-window enforcement.

mapping(uint32 dstChainId => mapping(address token => TransferInfo info)) public currentTransferSize

whitelistedMarkets

Market whitelist status.

mapping(address market => bool status) 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, bytes memory initData) ;

Parameters

NameTypeDescription
_rolesaddressRoles contract.
_saveAddressaddressAddress to sweep saved assets to.
_adminaddressAdmin address.
initDatabytesOptional initialization data (InitInfo ABI-encoded).

initFirewall

Initialize firewall.

function initFirewall(address _firewall) external;

Parameters

NameTypeDescription
_firewalladdressFirewall address.

setAdmin

Set admin.

function setAdmin(address _account) external;

Parameters

NameTypeDescription
_accountaddressAdmin address.

setSaveAddress

Set save address.

function setSaveAddress(address _save) external;

Parameters

NameTypeDescription
_saveaddressSave address.

setAllowedTokens

Set allowed tokens for a bridge.

function setAllowedTokens(address bridge, address[] calldata tokens, bool status)
    external
    onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
bridgeaddressBridge address.
tokensaddress[]Token list to allow/disallow.
statusboolAllowance status.

setMarketStatus

Batch whitelist/unwhitelist markets.

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

Parameters

NameTypeDescription
listaddress[]Market addresses.
statusboolWhitelist status.

setAllowList

Batch set allow-list status for markets.

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

Parameters

NameTypeDescription
listaddress[]Market addresses.
statusboolAllow list status.

setWhitelistedBridgeStatus

Set whitelist status for a bridge.

function setWhitelistedBridgeStatus(address _bridge, bool _status) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
_bridgeaddressBridge address.
_statusboolWhitelist status.

setWhitelistedDestination

Set whitelist status for a destination chain.

function setWhitelistedDestination(uint32 _dstId, bool _status) external onlyFirewallApprovedAllowEOA;

Parameters

NameTypeDescription
_dstIduint32Destination chain id.
_statusboolWhitelist status.

saveEth

Sweep native ETH to the configured save address.

function saveEth() external onlyFirewallApprovedAllowEOA;

saveTokens

Sweep stray tokens to the given market.

function saveTokens(address token, address market) external;

Parameters

NameTypeDescription
tokenaddressToken address to sweep.
marketaddressMarket to receive tokens.

setMinTransferSize

Sets the minimum transfer size for a given destination and token.

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

Parameters

NameTypeDescription
_dstChainIduint32Destination chain id.
_tokenaddressToken address.
_limituint256Minimum transfer size.

setMaxTransferSize

Sets the maximum transfer size for a given destination and token.

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

Parameters

NameTypeDescription
_dstChainIduint32Destination chain id.
_tokenaddressToken address.
_limituint256Maximum transfer size.

sendMsg

Sends a bridge message.

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

Parameters

NameTypeDescription
_bridgeaddress
_marketaddressThe market to rebalance from address.
_amountuint256The amount to rebalance.
_msgMsgThe message data.

isMarketWhitelisted

Returns if a market is whitelisted.

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

Parameters

NameTypeDescription
marketaddressMarket address.

Returns

NameTypeDescription
<none>boolwhitelisted True if whitelisted.

isBridgeWhitelisted

Returns if a bridge implementation is whitelisted.

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

Parameters

NameTypeDescription
bridgeaddressBridge address.

Returns

NameTypeDescription
<none>boolwhitelisted True if whitelisted.

isDestinationWhitelisted

Returns if a destination is whitelisted.

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

Parameters

NameTypeDescription
dstIduint32Destination chain ID.

Returns

NameTypeDescription
<none>boolwhitelisted True if whitelisted.

firewallRegister

Registers an account with the firewall.

function firewallRegister(address _account) public override(HypernativeFirewallProtected);

Parameters

NameTypeDescription
_accountaddressAccount to register.

_initFromData

Initializes the Rebalancer from initialization data.

function _initFromData(bytes memory initData) internal;

Parameters

NameTypeDescription
initDatabytesInitialization data.

_initMarkets

Initializes the markets.

function _initMarkets(address[] memory markets) internal;

Parameters

NameTypeDescription
marketsaddress[]Markets to initialize.

_initBridges

Initializes the bridges.

function _initBridges(address[] memory bridges) internal;

Parameters

NameTypeDescription
bridgesaddress[]Bridges to initialize.

_initDestinations

Initializes the destinations.

function _initDestinations(uint32[] memory destinations) internal;

Parameters

NameTypeDescription
destinationsuint32[]Destinations to initialize.

_initBridgeTokens

Initializes the bridge tokens.

function _initBridgeTokens(BridgeTokens[] memory bridgeTokens) internal;

Parameters

NameTypeDescription
bridgeTokensBridgeTokens[]Bridge tokens to initialize.

_sendMsgPreChecks

Checks the pre-conditions for sending a message.

function _sendMsgPreChecks(address _bridge, address _market, uint256 _amount, Msg calldata _msg) internal;

Parameters

NameTypeDescription
_bridgeaddressBridge address.
_marketaddressMarket address.
_amountuint256Amount to send.
_msgMsgMessage data.

_updateTransferWindowAndCheckMax

Updates the transfer window and checks the maximum transfer size.

function _updateTransferWindowAndCheckMax(uint256 amount, uint32 dstChainId, address token) internal;

Parameters

NameTypeDescription
amountuint256Amount to send.
dstChainIduint32Destination chain id.
tokenaddressToken address.

_setMarketStatus

Sets the market status.

function _setMarketStatus(address[] memory list, bool status) internal;

Parameters

NameTypeDescription
listaddress[]Market addresses.
statusboolMarket status.

_setAllowList

Sets the allow list.

function _setAllowList(address[] memory list, bool status) internal;

Parameters

NameTypeDescription
listaddress[]Market addresses.
statusboolAllow list status.

_setWhitelistedBridgeStatus

Sets the whitelisted bridge status.

function _setWhitelistedBridgeStatus(address _bridge, bool _status) internal;

Parameters

NameTypeDescription
_bridgeaddressBridge address.
_statusboolWhitelisted bridge status.

_setWhitelistedDestination

Sets the whitelisted destination.

function _setWhitelistedDestination(uint32 _dstId, bool _status) internal;

Parameters

NameTypeDescription
_dstIduint32Destination chain id.
_statusboolWhitelisted destination status.

_setAllowedTokens

Sets the allowed tokens.

function _setAllowedTokens(address bridge, address[] memory tokens, bool status) internal;

Parameters

NameTypeDescription
bridgeaddressBridge address.
tokensaddress[]Token addresses.
statusboolAllowed tokens status.

Structs

TransferInfo

struct TransferInfo {
    uint256 size;
    uint256 timestamp;
}

InitInfo

struct InitInfo {
    BridgeTokens[] bridgeTokens;
    address[] markets;
    address[] bridges;
    uint32[] destinations;
}

BridgeTokens

struct BridgeTokens {
    address bridge;
    address[] tokens;
}

Contents

ReferralSigning

Git Source

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

NameTypeDescription
signaturebytesUser's signature proving consent
referreraddressAddress of the referrer

Events

ReferralClaimed

Emitted when a referral is successfully claimed

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

Parameters

NameTypeDescription
referredaddressThe referred user
referreraddressThe referrer

ReferralRejected

Emitted when a referral claim is rejected

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

Parameters

NameTypeDescription
referredaddressThe referred user
referreraddressThe referrer
reasonstringRejection 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

Git Source

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

NameTypeDescription
_operatoraddressOperator address

notifySupplyIndex

Updates supply indices for all reward tokens on a market

function notifySupplyIndex(address mToken) external override onlyOperator;

Parameters

NameTypeDescription
mTokenaddressMarket token

notifyBorrowIndex

Updates borrow indices for all reward tokens on a market

function notifyBorrowIndex(address mToken) external override onlyOperator;

Parameters

NameTypeDescription
mTokenaddressMarket token

notifySupplier

Accrues supplier rewards for all reward tokens on a market

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

Parameters

NameTypeDescription
mTokenaddressMarket address
supplieraddressSupplier address

notifyBorrower

Accrues borrower rewards for all reward tokens on a market

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

Parameters

NameTypeDescription
mTokenaddressMarket address
borroweraddressBorrower address

initialize

Initializes the upgradeable contract

function initialize(address _owner) public initializer;

Parameters

NameTypeDescription
_owneraddressOwner address

grantReward

Grants reward to a user

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

Parameters

NameTypeDescription
tokenaddressReward token address
useraddressUser address
amountuint256Amount to grant

claim

Claims rewards for a list of holders across all reward tokens

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

Parameters

NameTypeDescription
holdersaddress[]Account list to claim for

whitelistToken

Whitelists a new reward token

function whitelistToken(address rewardToken_) public onlyOwner;

Parameters

NameTypeDescription
rewardToken_addressReward 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

NameTypeDescription
rewardToken_addressReward token address
mTokensaddress[]Market addresses
supplySpeedsuint256[]Supply speeds per market
borrowSpeedsuint256[]Borrow speeds per market

getBlockTimestamp

Get block timestamp

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

Returns

NameTypeDescription
<none>uint32timestamp Current block timestamp

getRewardTokens

Added reward tokens

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

Returns

NameTypeDescription
<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

NameTypeDescription
rewardTokenaddressReward token address
holdersaddress[]Holder list

_grantReward

Transfers accrued rewards to a user

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

Parameters

NameTypeDescription
tokenaddressReward token
useraddressRecipient address
amountuint256Amount to grant

Returns

NameTypeDescription
<none>uint256Remaining 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

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket address
supplySpeeduint256New supply speed
borrowSpeeduint256New borrow speed

_notifySupplyIndex

Updates supply index for a reward token/market pair

function _notifySupplyIndex(address rewardToken, address mToken) private;

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket address

_notifyBorrowIndex

Updates borrow index for a reward token/market pair

function _notifyBorrowIndex(address rewardToken, address mToken) private;

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket address

_notifySupplier

Accrues supplier rewards for a market

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket address
supplieraddressSupplier address

_notifyBorrower

Accrues borrower rewards for a market

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

Parameters

NameTypeDescription
rewardTokenaddressReward token address
mTokenaddressMarket address
borroweraddressBorrower 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

Git Source

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

NameTypeDescription
_adminaddressAddress 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

NameTypeDescription
newAdminaddressAddress 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

NameTypeDescription
_addraddressNew admin address

create

Deploys a contract using CREATE3

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

Parameters

NameTypeDescription
saltbytes32Deterministic salt used for CREATE3
codebytesCreation bytecode to deploy

Returns

NameTypeDescription
deployedaddressThe 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

NameTypeDescription
saltbytes32Deterministic salt used for CREATE3

Returns

NameTypeDescription
<none>addressThe address that would be deployed

Events

AdminSet

Emitted when admin is updated

event AdminSet(address indexed _admin);

Parameters

NameTypeDescription
_adminaddressNew admin address

PendingAdminSet

Emitted when pending admin is set

event PendingAdminSet(address indexed _admin);

Parameters

NameTypeDescription
_adminaddressPending admin address

AdminAccepted

Emitted when pending admin accepts control

event AdminAccepted(address indexed _admin);

Parameters

NameTypeDescription
_adminaddressThe admin address that just accepted

Errors

NotAuthorized

Error thrown when the caller is not the admin

error NotAuthorized(address admin, address sender);

ExponentialNoError

Git Source

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

NameTypeDescription
expExpThe exp to truncate.

Returns

NameTypeDescription
<none>uint256The 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

Git Source

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

NameTypeDescription
borroweraddressAddress of the borrower
marketaddressMarket address implementing ImToken

Returns

NameTypeDescription
shouldLiquidateboolTrue if borrower is below collateral requirements
repayAmountuint256Max repay amount according to close factor

IWrappedNative

Git Source

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

NameTypeDescription
toaddressReceiver address
valueuint256Amount to transfer

Returns

NameTypeDescription
<none>boolWhether the transfer succeeded

withdraw

Unwraps wrapped native tokens back to the native coin

function withdraw(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256Amount to unwrap

WrapAndSupply

Git Source

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

NameTypeDescription
_wrappedNativeaddressWrapped 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

NameTypeDescription
mTokenaddressThe market address
receiveraddressThe mToken receiver
minAmountuint256The 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

NameTypeDescription
mTokenGatewayaddressThe extension market address
receiveraddressThe receiver
selectorbytes4The host chain function selector

_wrap

Wraps a native coin into its wrapped version

function _wrap(uint256 amountToWrap) private;

Parameters

NameTypeDescription
amountToWrapuint256The 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

NameTypeDescription
senderaddressThe caller providing native funds
receiveraddressThe account receiving the minted mTokens
marketaddressThe market that received the wrapped assets
amountuint256The 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

Git Source

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

NameTypeDescription
journalEntrybytesThe Risc0 journal entry
sealbytesThe proof seal

ZkVerifier

Git Source

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

NameTypeDescription
owner_addressContract owner
_imageIdbytes32Risc0 image identifier
_verifieraddressRisc0 verifier contract address

setVerifier

Sets the _risc0Verifier address

Admin check is needed on the external method

function setVerifier(address _risc0Verifier) external onlyOwner;

Parameters

NameTypeDescription
_risc0Verifieraddressthe new IRiscZeroVerifier address

setImageId

Sets the image id

Admin check is needed on the external method

function setImageId(bytes32 _imageId) external onlyOwner;

Parameters

NameTypeDescription
_imageIdbytes32the new image id

verifyInput

Verifies an input

function verifyInput(bytes calldata journalEntry, bytes calldata seal) external view;

Parameters

NameTypeDescription
journalEntrybytesthe risc0 journal entry
sealbytesthe risc0 seal

Events

ImageSet

Emitted when the imageId is updated

event ImageSet(bytes32 _imageId);

Parameters

NameTypeDescription
_imageIdbytes32New image identifier

VerifierSet

Emitted when the verifier contract address is updated

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

Parameters

NameTypeDescription
oldVerifieraddressPrevious verifier address
newVerifieraddressNew 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

Git Source

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

NameTypeDescription
owner_addressOwner address

allowFor

Abiltity to allow a contract for a role or not

function allowFor(address _contract, bytes32 _role, bool _allowed) external onlyOwner;

Parameters

NameTypeDescription
_contractaddressthe contract's address.
_rolebytes32the bytes32 role.
_allowedboolthe new status.

isAllowedFor

Checks if a contract has a given role

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

Parameters

NameTypeDescription
_contractaddressContract address
_rolebytes32Role identifier

Returns

NameTypeDescription
<none>boolTrue if allowed

Events

Allowed

Emitted when role allowance is updated

event Allowed(address indexed _contract, bytes32 indexed _role, bool _allowed);

Parameters

NameTypeDescription
_contractaddressThe contract being updated
_rolebytes32The role identifier
_allowedboolNew allowance status