Skip to content
Verified contractPartialMIT

IrmRouter

Address0x683ea34c29658fb6cdecc92eb4b4e7f766979868
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,291,294
Creation transaction
0x1aaa57f223…49a807a738

lib/lido-lend-irm/src/irm-router/IrmRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;

import {IIrm} from "../../lib/lido-lend/src/interfaces/IIrm.sol";
import {IIrmRouter} from "./interfaces/IIrmRouter.sol";
import {Id, MarketParams, Market, IMorpho} from "../../lib/lido-lend/src/interfaces/IMorpho.sol";
import {MarketParamsLib} from "../../lib/lido-lend/src/libraries/MarketParamsLib.sol";
import {OwnerManagerBase} from "../common/OwnerManagerBase.sol";
import {OwnerManagerErrors} from "../common/OwnerManagerErrors.sol";
import {ErrorsLib} from "./libraries/ErrorsLib.sol";

/// @title IrmRouter
/// @author Lido.
/// @notice A market's `irm` can never change in Morpho, so markets are created pointing at this router. It forwards
/// `borrowRate`/`borrowRateView` to a per-market implementation switchable by the `owner` or `manager`, letting a
/// live market migrate between rate models.
/// @dev Runs behind a proxy. Implementations are immutable, constructed with this router as their trusted caller.
contract IrmRouter layout at erc7201("lido.lend.storage.IrmRouter") is IIrmRouter, OwnerManagerBase {
    using MarketParamsLib for MarketParams;

    // ---
    // IMMUTABLES
    // ---

    /// @inheritdoc IIrmRouter
    address public immutable MORPHO;

    // ---
    // STORAGE
    // ---

    /// @inheritdoc IIrmRouter
    bool public isInitialized;

    /// @inheritdoc IIrmRouter
    mapping(Id => IIrm) public marketIrm;

    // ---
    // CONSTRUCTOR
    // ---

    /// @param morpho The address of Morpho.
    constructor(address morpho) {
        require(morpho != address(0), OwnerManagerErrors.ZERO_ADDRESS);

        MORPHO = morpho;
        // Lock the implementation: only a proxy, whose storage starts zeroed, can be initialized.
        isInitialized = true;
    }

    // ---
    // INITIALIZATION
    // ---

    /// @inheritdoc IIrmRouter
    function initialize(address owner_, address manager_) external {
        require(!isInitialized, ErrorsLib.ALREADY_INITIALIZED);

        isInitialized = true;
        _transferOwnership(owner_);
        _setManager(manager_);
    }

    // ---
    // ROUTING
    // ---

    /// @inheritdoc IIrmRouter
    /// @dev A new market is routed without touching the implementation: `createMarket` performs the first
    /// `borrowRate` ping itself and reverts while the implementation is unconfigured or mis-gated, creating nothing.
    /// A live market is accrued first (the old model prices its own period) and the new implementation is probed
    /// with the exact call Morpho will make -- a reverting one would brick the market. Re-attaching a previously
    /// used `AdaptiveCurveIrm` resumes from its frozen `rateAtTarget`, not from `initialRateAtTarget`.
    function setMarketIrm(MarketParams memory marketParams, IIrm irm) external {
        _checkAuthorized();
        require(address(irm) != address(0), OwnerManagerErrors.ZERO_ADDRESS);
        // The id commits to the `irm` field: a foreign address would route a phantom market.
        require(marketParams.irm == address(this), ErrorsLib.NOT_ROUTER_MARKET);

        Id id = marketParams.id();

        // Only a live market is accrued and probed: a pre-creation probe would prematurely write a stateful
        // model's rateAtTarget, and a repeated one would then decay it over the whole epoch.
        Market memory market = IMorpho(MORPHO).market(id);
        if (market.lastUpdate != 0) {
            IMorpho(MORPHO).accrueInterest(marketParams);
            market = IMorpho(MORPHO).market(id);

            irm.borrowRate(marketParams, market);
        }

        marketIrm[id] = irm;
        emit MarketIrmSet(id, address(irm));
    }

    // ---
    // BORROW RATES
    // ---

    /// @inheritdoc IIrm
    function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256) {
        require(msg.sender == MORPHO, ErrorsLib.NOT_MORPHO);

        IIrm irm = marketIrm[marketParams.id()];
        require(address(irm) != address(0), ErrorsLib.IRM_NOT_SET);

        return irm.borrowRate(marketParams, market);
    }

    /// @inheritdoc IIrm
    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256) {
        IIrm irm = marketIrm[marketParams.id()];
        require(address(irm) != address(0), ErrorsLib.IRM_NOT_SET);

        return irm.borrowRateView(marketParams, market);
    }
}

lib/lido-lend-irm/lib/lido-lend/src/interfaces/IIrm.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {MarketParams, Market} from "./IMorpho.sol";

/// @title IIrm
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
interface IIrm {
    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
    /// @dev Assumes that `market` corresponds to `marketParams`.
    function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);

    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
    /// storage.
    /// @dev Assumes that `market` corresponds to `marketParams`.
    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
}

lib/lido-lend-irm/lib/lido-lend/src/interfaces/IMorpho.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

type Id is bytes32;

struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
    uint256 supplyShares;
    uint128 borrowShares;
    uint128 collateral;
}

/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

struct Authorization {
    address authorizer;
    address authorized;
    bool isAuthorized;
    uint256 nonce;
    uint256 deadline;
}

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

/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoBase {
    /// @notice The EIP-712 domain separator.
    /// @dev The separator is recomputed from the current chain id and `address(this)` on every call.
    /// @dev Warning: The domain does not distinguish deployments that have both the same chain id and the same contract
    /// address. Nonce state and authorization deadlines still apply.
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice The owner of the contract.
    /// @dev It has the power to change the owner.
    /// @dev It has the power to set fees on markets and set the fee recipient.
    /// @dev It has the power to create markets, which enables their IRMs and LLTVs.
    function owner() external view returns (address);

    /// @notice The fee recipient of all markets.
    /// @dev The recipient receives the fees of a given market through a supply position on that market.
    function feeRecipient() external view returns (address);

    /// @notice Whether the `irm` is enabled.
    /// @dev An IRM becomes enabled when the first market using it is created. It is not possible to disable an IRM.
    function isIrmEnabled(address irm) external view returns (bool);

    /// @notice Whether the `lltv` is enabled.
    /// @dev An LLTV becomes enabled when the first market using it is created. It is not possible to disable a LLTV.
    function isLltvEnabled(uint256 lltv) external view returns (bool);

    /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
    /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
    function isAuthorized(address authorizer, address authorized) external view returns (bool);

    /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
    function nonce(address authorizer) external view returns (uint256);

    /// @notice Sets `newOwner` as `owner` of the contract.
    /// @dev Warning: No two-step transfer ownership.
    /// @dev Warning: The owner can be set to the zero address.
    function setOwner(address newOwner) external;

    /// @notice Sets the `newFee` for the given market `marketParams`.
    /// @param newFee The new fee, scaled by WAD.
    /// @dev Warning: If `feeRecipient` is the zero address, a non-zero fee mints inaccessible shares to that address.
    function setFee(MarketParams memory marketParams, uint256 newFee) external;

    /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
    /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
    /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
    /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
    function setFeeRecipient(address newFeeRecipient) external;

    /// @notice Creates the market `marketParams`.
    /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
    /// Morpho behaves as expected:
    /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
    /// - The core's token balance should not decrease except through a transfer requested by the core. Arbitrary burns,
    /// negative rebases, and similar balance changes are not supported.
    /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
    /// - A successful `transfer` or `transferFrom` should decrease the sender's balance and increase the receiver's
    /// balance by exactly the requested amount. In particular, tokens with transfer fees are not supported.
    /// - The IRM should not re-enter Morpho.
    /// - The oracle should return a strictly positive price with the correct scaling.
    /// - The oracle price should not be able to change instantly such that the new price is less than the old price
    /// multiplied by LLTV*LIF. In particular, if the loan asset is a vault that can receive donations, the oracle
    /// should not price its shares using the AUM.
    /// @dev Here is a list of assumptions on the market's dependencies which, if broken, could break Morpho's liveness
    /// properties (funds could get stuck):
    /// - The token should not revert on `transfer` and `transferFrom` if balances and approvals are right.
    /// - The amount of assets supplied and borrowed should not be too high (max ~1e32), otherwise the number of shares
    /// might not fit within 128 bits.
    /// - The IRM should not revert on `borrowRate`.
    /// - The IRM should not return a very high borrow rate (otherwise the computation of `interest` in
    /// `_accrueInterest` can overflow).
    /// - The oracle should not revert `price`.
    /// - The oracle should not return a very high price (otherwise the computation of `maxBorrow` in `_isHealthy` or of
    /// `assetsRepaid` in `liquidate` can overflow).
    /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
    /// the point where `totalBorrowShares` is very large and borrowing overflows.
    /// @dev Warning: Can only be called by the owner. The created market has no controller; see the overload in
    /// `ILidoLend`.
    function createMarket(MarketParams memory marketParams) external;

    /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoSupply` function with the given `data`.
    /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
    /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
    /// amount of shares is given for full compatibility and precision.
    /// @dev Supplying a large amount can revert for overflow.
    /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
    /// Consider using the `assets` parameter to avoid this.
    /// @dev Warning: On a controlled market, this function calls the controller's `Supply` hook after interest accrual
    /// and before the supply-specific state changes. Every call that reaches hook dispatch checks the global hook lock,
    /// including calls on markets without a controller. The controller may revert to reject the action.
    /// @param marketParams The market to supply assets to.
    /// @param assets The amount of assets to supply.
    /// @param shares The amount of shares to mint.
    /// @param onBehalf The address that will own the increased supply position.
    /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
    /// @return assetsSupplied The amount of assets supplied.
    /// @return sharesSupplied The amount of shares minted.
    function supply(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);

    /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
    /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
    /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
    /// conversion roundings between shares and assets.
    /// @dev Warning: On a controlled market, this function calls the controller's `Withdraw` hook after interest
    /// accrual and before the withdrawal-specific state changes. Every call that reaches hook dispatch checks the
    /// global hook lock, including calls on markets without a controller. The controller may revert to reject the
    /// action.
    /// @param marketParams The market to withdraw assets from.
    /// @param assets The amount of assets to withdraw.
    /// @param shares The amount of shares to burn.
    /// @param onBehalf The address of the owner of the supply position.
    /// @param receiver The address that will receive the withdrawn assets.
    /// @return assetsWithdrawn The amount of assets withdrawn.
    /// @return sharesWithdrawn The amount of shares burned.
    function withdraw(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);

    /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
    /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
    /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
    /// given for full compatibility and precision.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Borrowing a large amount can revert for overflow.
    /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
    /// Consider using the `assets` parameter to avoid this.
    /// @dev Warning: On a controlled market, this function calls the controller's `Borrow` hook after interest accrual
    /// and before the borrow-specific state changes. Every call that reaches hook dispatch checks the global hook lock,
    /// including calls on markets without a controller. The controller may revert to reject the action.
    /// @param marketParams The market to borrow assets from.
    /// @param assets The amount of assets to borrow.
    /// @param shares The amount of shares to mint.
    /// @param onBehalf The address that will own the increased borrow position.
    /// @param receiver The address that will receive the borrowed assets.
    /// @return assetsBorrowed The amount of assets borrowed.
    /// @return sharesBorrowed The amount of shares minted.
    function borrow(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);

    /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoRepay` function with the given `data`.
    /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
    /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
    /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
    /// roundings between shares and assets.
    /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
    /// @dev Warning: On a controlled market, this function calls the controller's `Repay` hook after interest accrual
    /// and before the repayment-specific state changes. Every call that reaches hook dispatch checks the global hook
    /// lock, including calls on markets without a controller. The controller may revert to reject the action.
    /// @param marketParams The market to repay assets to.
    /// @param assets The amount of assets to repay.
    /// @param shares The amount of shares to burn.
    /// @param onBehalf The address of the owner of the debt position.
    /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
    /// @return assetsRepaid The amount of assets repaid.
    /// @return sharesRepaid The amount of shares burned.
    function repay(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);

    /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
    /// `onMorphoSupplyCollateral` function with the given `data`.
    /// @dev Interest is not accrued since it's not required and it saves gas.
    /// @dev Supplying a large amount can revert for overflow.
    /// @dev Warning: On a controlled market, this function calls the controller's `SupplyCollateral` hook before the
    /// collateral-specific state changes; this action does not accrue interest. Every call that reaches hook dispatch
    /// checks the global hook lock, including calls on markets without a controller. The controller may reject the
    /// action.
    /// @param marketParams The market to supply collateral to.
    /// @param assets The amount of collateral to supply.
    /// @param onBehalf The address that will own the increased collateral position.
    /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
    function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
        external;

    /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
    /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
    /// @dev Warning: On a controlled market, this function calls the controller's `WithdrawCollateral` hook after
    /// interest accrual and before the collateral-specific state changes. Every call that reaches hook dispatch checks
    /// the global hook lock, including calls on markets without a controller. The controller may reject the action.
    /// @param marketParams The market to withdraw collateral from.
    /// @param assets The amount of collateral to withdraw.
    /// @param onBehalf The address of the owner of the collateral position.
    /// @param receiver The address that will receive the collateral assets.
    function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
        external;

    /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
    /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
    /// `onMorphoLiquidate` function with the given `data`.
    /// @dev Either `seizedAssets` or `repaidShares` should be zero.
    /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
    /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
    /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
    /// @dev Warning: On a controlled market, this function calls the controller's `Liquidate` hook after interest
    /// accrual and before the liquidation-specific state changes. Every call that reaches hook dispatch checks the
    /// global hook lock, including calls on markets without a controller. The controller may reject the action.
    /// @param marketParams The market of the position.
    /// @param borrower The owner of the position.
    /// @param seizedAssets The amount of collateral to seize.
    /// @param repaidShares The amount of shares to repay.
    /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
    /// @return The amount of assets seized.
    /// @return The amount of assets repaid.
    function liquidate(
        MarketParams memory marketParams,
        address borrower,
        uint256 seizedAssets,
        uint256 repaidShares,
        bytes memory data
    ) external returns (uint256, uint256);

    /// @notice Executes a flash loan.
    /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
    /// markets combined, plus donations).
    /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
    /// - `flashFee` is zero.
    /// - `maxFlashLoan` is the token's balance of this contract.
    /// - The receiver of `assets` is the caller.
    /// @dev Warning: This function does not dispatch a controller hook or check the global hook lock. A controller can
    /// call it while another hooked action is waiting for that controller to return.
    /// @param token The token to flash loan.
    /// @param assets The amount of assets to flash loan.
    /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
    function flashLoan(address token, uint256 assets, bytes calldata data) external;

    /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
    /// @param authorized The authorized address.
    /// @param newIsAuthorized The new authorization status.
    function setAuthorization(address authorized, bool newIsAuthorized) external;

    /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
    /// @dev Warning: Reverts if the signature has already been submitted.
    /// @dev The signature is malleable, but it has no impact on the security here.
    /// @dev The nonce is passed as argument to be able to revert with a different error message.
    /// @param authorization The `Authorization` struct.
    /// @param signature The signature.
    function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;

    /// @notice Accrues interest for the given market `marketParams`.
    /// @dev Warning: On a controlled market, this function calls the controller's `AccrueInterest` hook before accruing
    /// interest. Every call that reaches hook dispatch checks the global hook lock, including calls on markets without
    /// a controller. The controller may revert to reject the action.
    function accrueInterest(MarketParams memory marketParams) external;

    /// @notice Returns the data stored on the different `slots`.
    function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
}

/// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoStaticTyping is IMorphoBase {
    /// @notice The state of the position of `user` on the market corresponding to `id`.
    /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
    /// accrual.
    function position(Id id, address user)
        external
        view
        returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);

    /// @notice The state of the market corresponding to `id`.
    /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
    /// accrual.
    function market(Id id)
        external
        view
        returns (
            uint128 totalSupplyAssets,
            uint128 totalSupplyShares,
            uint128 totalBorrowAssets,
            uint128 totalBorrowShares,
            uint128 lastUpdate,
            uint128 fee
        );

    /// @notice The market params corresponding to `id`.
    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
    function idToMarketParams(Id id)
        external
        view
        returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
}

/// @title IMorpho
/// @author Morpho Labs. Modified by Lido.
/// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
interface IMorpho is IMorphoBase {
    /// @notice The state of the position of `user` on the market corresponding to `id`.
    /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
    /// accrual.
    function position(Id id, address user) external view returns (Position memory p);

    /// @notice The state of the market corresponding to `id`.
    /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
    /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
    /// interest accrual.
    function market(Id id) external view returns (Market memory m);

    /// @notice The market params corresponding to `id`.
    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
    function idToMarketParams(Id id) external view returns (MarketParams memory);
}

lib/lido-lend-irm/lib/lido-lend/src/libraries/MarketParamsLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import {Id, MarketParams} from "../interfaces/IMorpho.sol";

/// @title MarketParamsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to convert a market to its id.
library MarketParamsLib {
    /// @notice The length of the data used to compute the id of a market.
    /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
    uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;

    /// @notice Returns the id of the market `marketParams`.
    function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
        assembly ("memory-safe") {
            marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
        }
    }
}

lib/lido-lend-irm/src/common/IOwnerManager.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

/// @title IOwnerManager
/// @author Lido.
/// @notice Two-role (owner + manager) access surface shared by the IRMs and the router.
interface IOwnerManager {
    /// @notice Emitted when `owner` is set or transferred.
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /// @notice Emitted when `manager` is set.
    event ManagerSet(address indexed manager);

    /// @notice Address of the owner.
    function owner() external view returns (address);

    /// @notice Address of the manager.
    function manager() external view returns (address);

    /// @notice Sets `owner` to `newOwner`. Owner only. Reverts on zero.
    function transferOwnership(address newOwner) external;

    /// @notice Sets `manager` to `newManager`. Owner only. Reverts on zero.
    function setManager(address newManager) external;
}

lib/lido-lend-irm/src/common/OwnerManagerBase.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;

import {IOwnerManager} from "./IOwnerManager.sol";
import {OwnerManagerErrors} from "./OwnerManagerErrors.sol";

/// @title OwnerManagerBase
/// @author Lido.
/// @notice Two-role access base: the `owner` rotates itself and the `manager`, the `manager` shares only the
/// operational setters.
/// @dev Derived contracts set the initial roles via `_transferOwnership`/`_setManager` and gate functions with
/// `_checkOwner` or `_checkAuthorized`.
abstract contract OwnerManagerBase is IOwnerManager {
    // ---
    // STORAGE
    // ---

    /// @inheritdoc IOwnerManager
    address public override owner;

    /// @inheritdoc IOwnerManager
    address public override manager;

    // ---
    // OWNERSHIP & MANAGEMENT
    // ---

    /// @inheritdoc IOwnerManager
    function transferOwnership(address newOwner) external override {
        _checkOwner();
        _transferOwnership(newOwner);
    }

    /// @inheritdoc IOwnerManager
    function setManager(address newManager) external override {
        _checkOwner();
        _setManager(newManager);
    }

    /// @dev Reverts unless the caller is the owner.
    function _checkOwner() internal view {
        require(msg.sender == owner, OwnerManagerErrors.NOT_OWNER);
    }

    /// @dev Reverts unless the caller is the owner or the manager.
    function _checkAuthorized() internal view {
        require(msg.sender == owner || msg.sender == manager, OwnerManagerErrors.NOT_AUTHORIZED);
    }

    /// @dev Sets `owner`, reverting on the zero address.
    function _transferOwnership(address newOwner) internal {
        require(newOwner != address(0), OwnerManagerErrors.ZERO_ADDRESS);

        address previousOwner = owner;
        owner = newOwner;
        emit OwnershipTransferred(previousOwner, newOwner);
    }

    /// @dev Sets `manager`, reverting on the zero address.
    function _setManager(address newManager) internal {
        require(newManager != address(0), OwnerManagerErrors.ZERO_ADDRESS);

        manager = newManager;
        emit ManagerSet(newManager);
    }
}

lib/lido-lend-irm/src/common/OwnerManagerErrors.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title OwnerManagerErrors
/// @author Lido.
/// @notice Error messages for the `OwnerManagerBase` roles.
library OwnerManagerErrors {
    /// @dev Thrown when passing the zero address.
    string internal constant ZERO_ADDRESS = "zero address";

    /// @dev Thrown when the caller of an owner-only function is not the owner.
    string internal constant NOT_OWNER = "not owner";

    /// @dev Thrown when the caller of a param setter is neither the owner nor the manager.
    string internal constant NOT_AUTHORIZED = "not authorized";
}

lib/lido-lend-irm/src/irm-router/interfaces/IIrmRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

import {IIrm} from "../../../lib/lido-lend/src/interfaces/IIrm.sol";
import {Id, MarketParams} from "../../../lib/lido-lend/src/interfaces/IMorpho.sol";
import {IOwnerManager} from "../../common/IOwnerManager.sol";

/// @title IIrmRouter
/// @author Lido.
/// @notice Interface of the IrmRouter: forwards a market's `borrowRate`/`borrowRateView` to a switchable
/// per-market implementation. Proxied, so the roles are set via `initialize`.
interface IIrmRouter is IIrm, IOwnerManager {
    /// @notice Emitted when market `id` is routed to `irm`.
    event MarketIrmSet(Id indexed id, address indexed irm);

    /// @notice Address of Morpho.
    function MORPHO() external view returns (address);

    /// @notice Whether the contract has been initialized. True on the implementation from construction (locking it)
    /// and on the proxy after `initialize`.
    function isInitialized() external view returns (bool);

    /// @notice Sets `owner` and `manager` once, reverting if already initialized or either address is zero. Must run
    /// atomically with proxy deployment.
    function initialize(address owner_, address manager_) external;

    /// @notice The IRM implementation serving market `id` (zero if none). Re-pointable but never clearable, so a
    /// live market always has an implementation.
    function marketIrm(Id id) external view returns (IIrm);

    /// @notice Routes market `id = marketParams.id()` to `irm`. Owner or manager only.
    function setMarketIrm(MarketParams memory marketParams, IIrm irm) external;
}

lib/lido-lend-irm/src/irm-router/libraries/ErrorsLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title ErrorsLib
/// @author Lido.
/// @notice Errors of the IrmRouter.
library ErrorsLib {
    /// @notice Thrown when `initialize` is called after the contract is already initialized.
    string internal constant ALREADY_INITIALIZED = "already initialized";

    /// @notice Thrown when `borrowRate` is called by an address other than Morpho.
    string internal constant NOT_MORPHO = "not Morpho";

    /// @notice Thrown when pricing a market that has not been routed to an implementation.
    string internal constant IRM_NOT_SET = "irm not set";

    /// @notice Thrown when routing marketParams whose `irm` field is not this router.
    string internal constant NOT_ROUTER_MARKET = "irm is not this router";
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@circuit-breaker/=lib/circuit-breaker/",
    "@lido-lend-irm/=lib/lido-lend-irm/",
    "@lido-lend/=lib/lido-lend/",
    "@vault-v2/=lib/vault-v2/",
    "forge-std/=lib/vault-v2/lib/forge-std/src/",
    "@bundler3/=lib/bundler3/",
    "lib/bundler3/:solmate/=lib/bundler3/lib/permit2/lib/solmate/",
    "bundler3/=lib/bundler3/",
    "circuit-breaker/=lib/circuit-breaker/",
    "ds-test/=lib/lido-lend/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/bundler3/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lido-lend-irm/=lib/lido-lend-irm/",
    "lido-lend/=lib/lido-lend/",
    "metamorpho-v1.1/=lib/vault-v2/lib/metamorpho-v1.1/",
    "metamorpho/=lib/vault-v2/lib/metamorpho/",
    "morpho-blue-irm/=lib/vault-v2/lib/morpho-blue-irm/",
    "morpho-blue/=lib/vault-v2/lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "permit2/=lib/bundler3/lib/permit2/",
    "solmate/=lib/lido-lend-irm/lib/solmate/src/",
    "vault-v2/=lib/vault-v2/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.