Skip to content
Verified contractExactBUSL-1.1

CumulativeIndexBorrowMorpho

Address0x037c26656c63008efdf18712e284bed95fd31014
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,401,456
Creation transaction
0xd9cd24a576…4786360efb

contracts/v1.1/oracles/cumulativeIndex/CumulativeIndexBorrowMorpho.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

/// @title CumulativeIndexBorrowMorpho
/// @notice Adapter that exposes Morpho Blue's borrow share exchange rate as a cumulative oracle.
///         The ratio totalBorrowAssets / totalBorrowShares naturally grows as interest accrues,
///         making it a cumulative borrow index.
/// @dev Projects the index forward using Morpho's own interest formula (3-term Taylor series)
///      when stale. If the projection cannot be computed (IRM or params call reverts), reports
///      isValid=false so settlement-critical callers reject the data rather than silently
///      using a stale share ratio.
///
///      Known limitation: Morpho rounds borrow-share minting up and repay-share burning down.
///      This asymmetric rounding can cause the share-price index to decrease by sub-wei amounts
///      per operation, even when the borrow rate is non-negative. Over 1 year of hourly
///      borrow/repay churn, measured drift is ~0.000000094% — negligible for swap settlement.
///      This approach is still more accurate than a SpotCompoundRate alternative, which
///      introduces sampling error that scales with update frequency and rate volatility.
///
///      Exposure floors: the borrow-side ratio is not a lifetime accumulator —
///      a fully repaid borrow side resets it to the virtual-offset baseline, and dust-level
///      totals make it sensitive to per-operation rounding residue. Readings where the raw
///      borrow side sits below the configured minAssets/minShares therefore report
///      isValid=false (see AbstractCumulativeIndexMorpho.minAssets).
contract CumulativeIndexBorrowMorpho is AbstractCumulativeIndexMorpho {
    constructor(
        address _morpho,
        bytes32 _marketId,
        uint256 _minAssets,
        uint256 _minShares,
        string memory description_
    ) AbstractCumulativeIndexMorpho(_morpho, _marketId, _minAssets, _minShares, description_) {}

    function getCumulativeIndex() external view returns (uint256 cumulativeIndex, bool isValid) {
        try morpho.market(marketId) returns (Market memory m) {
            if (m.lastUpdate == 0) return (0, false); // non-existent market

            uint256 borrowAssets = uint256(m.totalBorrowAssets);
            uint256 borrowShares = uint256(m.totalBorrowShares);

            // Below-floor borrow side: the share ratio is virtual-offset/dust-dominated and
            // no longer measures interest accrual — fail closed (epoch boundary, not data).
            if (_belowExposureFloor(borrowAssets, borrowShares)) return (0, false);

            // Project forward if stale. If projection fails, surface that to the caller
            // — do NOT return a stale share ratio with isValid=true.
            uint256 elapsed = block.timestamp - uint256(m.lastUpdate);
            if (elapsed > 0 && borrowAssets > 0) {
                bool ok;
                (borrowAssets, ok) = _tryProject(borrowAssets, m, elapsed);
                if (!ok) return (0, false);
            }

            // Borrow exchange rate: value of one share in assets, scaled by 1e27.
            // Starts at ~1e21 due to Morpho's VIRTUAL_SHARES (1e6). This does not affect
            // RateIndexLib correctness — rate derivation uses index ratios, so scale cancels.
            uint256 index = (borrowAssets + VIRTUAL_ASSETS) * 1e27
                / (borrowShares + VIRTUAL_SHARES);
            return (index, index > 0);
        } catch {
            return (0, false);
        }
    }

    /// @dev Attempts to project totalBorrowAssets forward using the IRM rate + Taylor series.
    ///      Returns (projected, true) on success.
    ///      Returns (borrowAssets, true) when params.irm == address(0) — no IRM means no
    ///      accrual, so the unprojected value is the current value (genuinely valid).
    ///      Returns (0, false) when idToMarketParams or borrowRateView reverts — the current
    ///      index is unknowable and callers must treat the reading as invalid.
    function _tryProject(
        uint256 borrowAssets,
        Market memory m,
        uint256 elapsed
    ) private view returns (uint256, bool) {
        try morpho.idToMarketParams(marketId) returns (MarketParams memory params) {
            if (params.irm == address(0)) return (borrowAssets, true);
            try IIrm(params.irm).borrowRateView(params, m) returns (uint256 rate) {
                // Replicate Morpho's _accrueInterest: interest = assets * wTaylorCompounded(rate * elapsed)
                uint256 interest = borrowAssets * _wTaylorCompounded(rate * elapsed) / WAD;
                return (borrowAssets + interest, true);
            } catch {
                return (0, false); // IRM failed — projection unknowable
            }
        } catch {
            return (0, false); // idToMarketParams failed — projection unknowable
        }
    }
}

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

contracts/interfaces/External.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

interface IChainlinkOracle {
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
}

/// @notice Shared metadata for all Kairos oracle types.
/// @dev Implementations that may be wrapped by `BaseUpgradableOracleWrapper` must
///      additionally implement ERC-165 `supportsInterface(bytes4)` advertising both
///      `IOracleMetadata` and the specific read interface they implement
///      (`IRateOracle` / `ITenorRateOracle` / `ICumulativeRateOracle`).
///      This is intentionally not enforced by the interface itself so existing
///      non-wrapped oracles continue to compile unchanged.
interface IOracleMetadata {
    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
}

/// @notice Read-only rate oracle — provides a single spot rate
/// @dev Precondition for adapters backing a RateConvention.SpotRate or .SpotCompoundRate market:
///      getRate() MUST clamp (saturate, never revert or return isValid=false) readings below a
///      feed-specific negative floor. RateIndexLib accumulates rate·time into an index floored at
///      MIN_INDEX; unbounded negative accrual pins the index to that floor, and BOTH spot conventions
///      then understate the floating leg at settlement because accrual below the floor is dropped.
///      A floor bounds the decay rate and keeps the pinned regime unreachable in practice. See the
///      RateConvention notes in Types.sol. Returning isValid=false instead of clamping bricks index
///      updates and blocks settlement, so the bound must saturate.
///      The first-party adapters carry a constructor-configured `minRateWad` for exactly this
///      (ChainlinkAdapter, PythAdapter); a third-party adapter must implement the same saturation.
///      Note this is an accounting bound, not a liveness one: deriveRateFromIndex takes the
///      SpotCompoundRate log as a difference of logs on the raw indices, so a floored index no longer
///      truncates a ratio to 0 and can no longer revert settlement/liquidation/MTM.
interface IRateOracle is IOracleMetadata {
    function getRate() external view returns (int256 rate, bool isValid);
}

/// @notice Unified tenor-dependent rate oracle — used for both base rate and risk rate oracles
interface ITenorRateOracle is IOracleMetadata {
    function getRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid);
    /// @notice Batch variant — returns interpolated rates for multiple tenors in a single call.
    ///         Used by SwapCore on the LP MtM critical path to amortise external-call overhead.
    function getRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid);
}

/// @notice Optional capability advertised by a base-rate oracle whose per-tenor quote is a full-tenor
///         compounded-equivalent (bumped) rate B — i.e. B·tenor/YEAR == exp(r·tenor/YEAR) − 1. A `true`
///         answer tells the interim (accrued-only) valuation to accrue the fixed leg on the compounded
///         curve so it tracks a convex Cumulative floating leg; oracles quoting an un-bumped rate return
///         `false` (or omit this interface, treated as `false`) and keep straight-line accrual. `false`
///         attests only that the bump is absent, not the rate's representation: a simple annual rate
///         and an un-bumped continuously compounded rate (e.g. `RawIndexBaseRateV1`) both return it.
///
/// @dev    IMPLEMENTER CONTRACT for a `true` return: the per-tenor rate B returned by `getRateByTenor`
///         MUST satisfy the identity `1 + B·tenor/YEAR == exp(r·tenor/YEAR)`, where `r` is the
///         continuously-compounded rate the quote represents. The consuming valuation recovers
///         `r = ln(1 + B·tenor/YEAR)·YEAR/tenor` and re-accrues as `exp(r·elapsed/YEAR) − 1`
///         (see `SwapFormulas.calculateCompoundAccruedFixedPayment`), so the compounded mark is only
///         correct when B was produced by exactly this bump. An oracle that returns `true` but bumps
///         with a different convention is still valued far more accurately than a `false`/straight-line
///         quote (the error is the small gap between two nearby convex curves, and it vanishes at
///         maturity where both collapse to the straight line), but a NEW opt-in oracle SHOULD match the
///         identity above — verify it with a round-trip test before pointing a market at it.
interface ICompoundedTenorQuote {
    function isCompoundedTenorQuote() external view returns (bool);
}

/// @notice Attestation binding a base-rate oracle to the SINGLE observation ring whose
///         snapshots produce its per-tenor quote. The compounded (BUY_FIXED) base oracle and
///         its raw (BUY_FLOATING) counterpart of a Cumulative market pair MUST report the same
///         ring address, so both quotes are two transforms — `(exp(r·T/YEAR) − 1)·YEAR/T` and
///         `r` — of ONE realized reading. Because the bump is convex (`exp(x) − 1 ≥ x`), a shared
///         reading guarantees `compoundedQuote ≥ rawQuote` at every block, which makes a paired
///         equal-notional BUY_FIXED + BUY_FLOATING position (whose floating legs cancel on the
///         shared reference index) always loss-making — closing the independent-ring inversion
///         and, with it, the transient-liquidity amplification that depended on it.
/// @dev    `baseRateRing()` returns `address(0)` for an oracle with no such ring (e.g. a
///         Chainlink-fed spot oracle). `createMarket` rejects a pair where either side advertises
///         a ring but the two do not resolve to the same non-zero ring (E615). Self-attested, like
///         `ICompoundedTenorQuote`: it guards against wiring two independent rings, not against an
///         oracle that lies about its ring — base oracles wired into a market are already trusted
///         for pricing correctness. The canonical `RawIndexBaseRateV1` / `RawMorphoBaseRateV1`
///         prove the relationship structurally: they hold no ring of their own and read their
///         compounded parent's, so their `baseRateRing()` cannot diverge from what they quote.
interface ISharedRingBaseRate {
    function baseRateRing() external view returns (address);
}

/// @notice Dual-sided premium oracle — exposes per-tenor "upper" (BUY_FIXED) and
///         "lower" (BUY_FLOATING) premiums from a single posting. Read by side-flagged
///         wrappers; SwapCore points each market side at its corresponding wrapper.
interface IDualSidedPremiumOracle is IOracleMetadata {
    function getUpRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid);
    function getLoRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid);
    function getUpRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid);
    function getLoRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid);
}

/// @notice For reference rate oracles that provide a cumulative index directly.
///         The cumulative index represents the total growth factor since some epoch,
///         normalized to RAY scale (1e27). Each adapter matches its source's native
///         convention (compound for Aave, simple for stETH, etc.).
interface ICumulativeRateOracle is IOracleMetadata {
    function getCumulativeIndex() external view returns (uint256 cumulativeIndex, bool isValid);
}

/// @notice Oracles that expose a permissionless keeper hook to advance their own
///         internal state (e.g. a TWAR ring buffer's observations). SwapCore opportunistically
///         calls this from `updateMarketRateIndex` and at market creation for any oracle slot
///         that advertises this interface via ERC-165. Implementations should be safe to call
///         from anyone and cheap to reject when called too early (e.g. revert `TooEarly`).
///         Pokeable oracles MUST also advertise `IPokeable` via `supportsInterface`.
/// @dev Read-invariance contract. poke() may only advance internal history: it MUST NOT
///      change the value of a valid read and MUST NOT invalidate one. It may restore a read
///      that was invalid or reverting (a ring past its liveness gap), which is safe because
///      no consumer prices an invalid read. SwapCore reads oracles from views that cannot
///      poke and pokes from permissionless paths, so a value that steps at poke would let
///      anyone mark against the un-poked quote and settle against the post-poke one.
///      Non-pokeable feeds satisfy this trivially.
interface IPokeable {
    function poke() external;
}

contracts/oracles/cumulativeIndex/AbstractCumulativeIndex.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import { ICumulativeRateOracle, IOracleMetadata } from "../../interfaces/External.sol";

/// @title AbstractCumulativeIndex
/// @notice Base contract for cumulative index oracle adapters.
///         Provides shared boilerplate: description storage and ERC-165 advertisement.
///         Children must implement getCumulativeIndex() and decimals().
/// @dev Inherits ERC165 and advertises both IOracleMetadata and ICumulativeRateOracle
///      (UpgradableCumulativeRateOracle's _requireDownstreamInterface() gates on
///      ERC-165 support at construction, queue, and activation). The advertisement is retained
///      for uniform introspection and the interface-gate regression tests, but note
///      the deployment policy documented on UpgradableCumulativeRateOracle: these adapters are consumed DIRECTLY as a
///      market's referenceRateOracle — the upgradable wrapper must NOT be deployed in front
///      of them in that slot (a downstream repoint would splice unrelated absolute index
///      levels under one RateIndexLib history key). Every cumulative adapter
///      (Aave/Compound/Morpho) inherits this, so the advertisement is shared in one place.
abstract contract AbstractCumulativeIndex is ERC165, ICumulativeRateOracle {
    string private _description;

    constructor(string memory description_) {
        _description = description_;
    }

    function description() external view returns (string memory) {
        return _description;
    }

    /// @inheritdoc ERC165
    /// @dev Advertises the oracle interfaces the upgradable wrapper requires
    ///      (IOracleMetadata + ICumulativeRateOracle); IERC165 itself is handled by super.
    function supportsInterface(bytes4 interfaceId)
        public
        view
        virtual
        override(ERC165)
        returns (bool)
    {
        return interfaceId == type(IOracleMetadata).interfaceId
            || interfaceId == type(ICumulativeRateOracle).interfaceId
            || super.supportsInterface(interfaceId);
    }
}

contracts/v1.1/oracles/cumulativeIndex/AbstractCumulativeIndexMorpho.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

import { AbstractCumulativeIndex } from "../../../oracles/cumulativeIndex/AbstractCumulativeIndex.sol";

/// @dev Morpho Blue market state — matches Morpho's on-chain struct layout
struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

/// @dev Morpho Blue market parameters — needed for IRM calls
struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

/// @notice Minimal interface for the Morpho Blue core contract
interface IMorpho {
    function market(bytes32 id) external view returns (Market memory);
    function idToMarketParams(bytes32 id) external view returns (MarketParams memory);
}

/// @notice Minimal interface for Morpho Blue Interest Rate Model
interface IIrm {
    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
}

/// @title AbstractCumulativeIndexMorpho
/// @notice Base contract for Morpho Blue cumulative index adapters (borrow & supply).
///         Consolidates shared Morpho types, constants, state, and the Taylor series helper.
///         Children only need to implement getCumulativeIndex().
abstract contract AbstractCumulativeIndexMorpho is AbstractCumulativeIndex {
    IMorpho public immutable morpho;
    bytes32 public immutable marketId;

    /// @dev Morpho Blue virtual offsets from SharesMathLib — prevent division by zero
    ///      and first-depositor inflation attacks
    uint256 internal constant VIRTUAL_ASSETS = 1;
    uint256 internal constant VIRTUAL_SHARES = 1e6;

    uint256 internal constant WAD = 1e18;

    /// @notice Exposure floors below which getCumulativeIndex() fails closed.
    /// @dev Unlike Aave's protocol-level accumulator, the Morpho share ratio is only a
    ///      trustworthy cumulative index while its side carries real exposure. Near zero the
    ///      ratio is dominated by the virtual offsets and per-operation rounding residue:
    ///      a fully repaid/withdrawn side resets the ratio to the virtual-offset baseline
    ///      (~1e21), and dust-level share totals let supplier-favorable rounding residue move
    ///      the ratio without any interest accruing. Both readings would be recorded (or
    ///      monotone-clamped against) as if they were genuine index movement. Below the
    ///      floors the adapter reports isValid=false instead; RateIndexLib.update() then
    ///      reverts E606, making a full unwind of the source a hard epoch boundary — no
    ///      baseline reset is spliced into the recorded history, and the old high-water is
    ///      never silently reused against post-reset exposure. Size the floors to the
    ///      smallest economically meaningful side (e.g. one whole loan-token unit of assets
    ///      and the matching minAssets × VIRTUAL_SHARES of shares); they are a dust/epoch
    ///      gate, not a market-depth guard — depth relative to Kairos exposure is an
    ///      operational concern, monitored off-chain.
    uint256 public immutable minAssets;
    uint256 public immutable minShares;

    constructor(
        address _morpho,
        bytes32 _marketId,
        uint256 _minAssets,
        uint256 _minShares,
        string memory description_
    ) AbstractCumulativeIndex(description_) {
        require(_morpho != address(0), "Invalid morpho");
        require(_minAssets > 0, "Invalid minAssets");
        // At minShares == VIRTUAL_SHARES the virtual offset is already half the denominator;
        // anything smaller would let it dominate and defeat the floor entirely.
        require(_minShares >= VIRTUAL_SHARES, "Invalid minShares");
        morpho = IMorpho(_morpho);
        marketId = _marketId;
        minAssets = _minAssets;
        minShares = _minShares;
    }

    /// @dev True when a side's raw (pre-projection) totals sit below the configured floors.
    ///      Checked against raw values on purpose: projection only inflates assets, so the
    ///      raw reading is the strictest test of whether real exposure backs the ratio.
    function _belowExposureFloor(uint256 assets, uint256 shares) internal view returns (bool) {
        return assets < minAssets || shares < minShares;
    }

    /// @dev Informational only — RateIndexLib does not use decimals() for Cumulative convention
    ///      (rate derivation divides one index by another, so the scale cancels).
    ///      The index is assets-per-share scaled by exactly 1e27, so 27 is the accurate value.
    ///      Note the level itself starts near 1e21, not 1e27: Morpho's VIRTUAL_SHARES (1e6)
    ///      makes one share worth ~1e-6 assets in an empty market. That is a property of the
    ///      quantity being measured, not of its encoding — consumers scaling the raw index by
    ///      10**decimals() must use 27 or they misread it by 1e9.
    function decimals() external pure returns (uint8) {
        return 27;
    }

    /// @dev 3-term Taylor series approximation of e^x - 1, matching Morpho's MathLib.
    ///      wTaylorCompounded(x) = x + x²/2 + x³/6
    function _wTaylorCompounded(uint256 x) internal pure returns (uint256) {
        uint256 firstTerm = x;
        uint256 secondTerm = x * x / 2 / WAD;
        uint256 thirdTerm = secondTerm * x / 3 / WAD;
        return firstTerm + secondTerm + thirdTerm;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.