Morpho Internals Part 3: What one oracle price buys

Turn a wstETH price into six-decimal USDC, follow the units through two feeds and see which side of the fraction changes when USDC moves.

ret2basic.eth (reviewed by jesjupyter)11 min read
Morpho Internals Part 3: What one oracle price buys

If one wstETH is worth 3,090 USDC, why does Morpho's oracle return 3,090×10243{,}090\times10^{24}? The borrower posts the collateral in 18-decimal units. The loan is recorded in six-decimal USDC. price() has to take the core from one set of integer units to the other, with a further 103610^{36} scale that Morpho removes at the end. A correct quote for one whole token is a quick way to catch a reversed feed or a misplaced power of ten.

Recall that there are two occurrences where oracle.price() gets invoked in Morpho.sol. The first occurrence is in liquidate():

solidity
    function liquidate(
        MarketParams memory marketParams,
        address borrower,
        uint256 seizedAssets,
        uint256 repaidShares,
        bytes calldata data
    ) external returns (uint256, uint256) {
        Id id = marketParams.id();
        require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
        require(UtilsLib.exactlyOneZero(seizedAssets, repaidShares), ErrorsLib.INCONSISTENT_INPUT);

        _accrueInterest(marketParams, id);

        {
            uint256 collateralPrice = IOracle(marketParams.oracle).price();

            require(!_isHealthy(marketParams, id, borrower, collateralPrice), ErrorsLib.HEALTHY_POSITION);
            ...

Note that fetching collateral price first and then calling the 4-parameter version of _isHealthy() is the same as calling the 3-parameter version of _isHealthy() directly:

solidity
    function _isHealthy(MarketParams memory marketParams, Id id, address borrower) internal view returns (bool) {
        if (position[id][borrower].borrowShares == 0) return true;

        uint256 collateralPrice = IOracle(marketParams.oracle).price();

        return _isHealthy(marketParams, id, borrower, collateralPrice);
    }

oracle.price() is also invoked in borrow() and withdrawCollateral() implicitly since they call the 3-parameter version of _isHealthy().

The core uses the quote to test borrowing capacity and to convert between repaid debt and seized collateral during liquidation. The three-argument health check returns immediately for a position with zero borrow shares. Interest accrual reads the IRM, and ordinary supply-share conversions use market totals. Morpho Blue health and liquidation calculations

Factory and oracle.price()#

Morpho provides a factory (MorphoChainlinkOracleV2Factory.sol) that allows users to deploy customized oracles themselves:

solidity
    function createMorphoChainlinkOracleV2(
        IERC4626 baseVault,
        uint256 baseVaultConversionSample,
        AggregatorV3Interface baseFeed1,
        AggregatorV3Interface baseFeed2,
        uint256 baseTokenDecimals,
        IERC4626 quoteVault,
        uint256 quoteVaultConversionSample,
        AggregatorV3Interface quoteFeed1,
        AggregatorV3Interface quoteFeed2,
        uint256 quoteTokenDecimals,
        bytes32 salt
    ) external returns (IMorphoChainlinkOracleV2 oracle) {
        oracle = new MorphoChainlinkOracleV2{salt: salt}(
            baseVault,
            baseVaultConversionSample,
            baseFeed1,
            baseFeed2,
            baseTokenDecimals,
            quoteVault,
            quoteVaultConversionSample,
            quoteFeed1,
            quoteFeed2,
            quoteTokenDecimals
        );

        isMorphoChainlinkOracleV2[address(oracle)] = true;
    }

In the oracle implementation, price() is the only function (besides the constructor) in MorphoChainlinkOracleV2.sol:

solidity
    function price() external view returns (uint256) {
        return SCALE_FACTOR.mulDiv(
            BASE_VAULT.getAssets(BASE_VAULT_CONVERSION_SAMPLE) * BASE_FEED_1.getPrice() * BASE_FEED_2.getPrice(),
            QUOTE_VAULT.getAssets(QUOTE_VAULT_CONVERSION_SAMPLE) * QUOTE_FEED_1.getPrice() * QUOTE_FEED_2.getPrice()
        );
    }

mulDiv is OpenZeppelin's (x * y) / z with full 512-bit intermediate precision — so SCALE_FACTOR.mulDiv(baseLeg, quoteLeg) computes SCALE_FACTOR * baseLeg / quoteLeg without overflow on the intermediate product.

To check a configured oracle, write down the unit of each leg before multiplying any feed answers.

From a bird's-eye view, price() can be read as one ratio:

price()  =  ⌊SCALE_FACTOR⋅(base leg)(quote leg)⌋\mathtt{price()}\;=\;\Big\lfloor\frac{\texttt{SCALE\_FACTOR}\cdot(\text{base leg})}{(\text{quote leg})}\Big\rfloor

where:

  • base leg = BASE_VAULT.getAssets(sample) * BASE_FEED_1.getPrice() * BASE_FEED_2.getPrice()
  • quote leg = QUOTE_VAULT.getAssets(sample) * QUOTE_FEED_1.getPrice() * QUOTE_FEED_2.getPrice()

Everything else in the contract is just “wiring” those legs and precomputing SCALE_FACTOR so the output lands in Morpho’s expected format.

Morpho’s Chainlink oracle does not talk to Chainlink feeds directly; it goes through ChainlinkDataFeedLib.

solidity
library ChainlinkDataFeedLib {
    /// @dev Performs safety checks and returns the latest price of a `feed`.
    /// @dev When `feed` is the address zero, returns 1.
    /// @dev Notes on safety checks:
    /// - L2s are not supported.
    /// - Staleness is not checked because it's assumed that the Chainlink feed keeps its promises on this.
    /// - The price is not checked to be in the min/max bounds because it's assumed that the Chainlink feed keeps its
    /// promises on this.
    function getPrice(AggregatorV3Interface feed) internal view returns (uint256) {
        if (address(feed) == address(0)) return 1;

        (, int256 answer,,,) = feed.latestRoundData();
        require(answer >= 0, ErrorsLib.NEGATIVE_ANSWER);

        return uint256(answer);
    }

    /// @dev Returns the number of decimals of a `feed`.
    /// @dev When `feed` is the address zero, returns 0.
    function getDecimals(AggregatorV3Interface feed) internal view returns (uint256) {
        if (address(feed) == address(0)) return 0;

        return feed.decimals();
    }
}

Reading that library clarifies several behavioral details that are easy to miss:

  • feed.latestRoundData() is called and only answer is used.
  • The library accepts zero and rejects negative answers. A zero base feed makes the numerator zero. A zero quote feed makes the denominator zero, so the price calculation reverts. These outcomes assume the other factors are valid.
  • The library reads the answer without enforcing a maximum age using updatedAt. Freshness assumptions belong to the chosen feeds and any additional checks in the integration.
  • When a feed address is address(0), getPrice() returns 1 (a multiplicative no-op), and getDecimals() returns 0.

The “address(0) means 1” convention is the key that makes “0/1/2 feeds per leg” possible with a single code path.

What does one raw collateral unit buy?#

As per the doc, Morpho expects oracle.price() to be:

Morpho oracle price units converting collateral into loan assets with 1e36 scaling

This is exactly why Morpho stores it in a local variable named collateralPrice.

solidity
// Morpho.sol
uint256 collateralPrice = IOracle(marketParams.oracle).price();

Morpho later consumes the oracle output by converting collateral → loan units using:

solidity
// Morpho.sol
uint256 maxBorrow = collateral.mulDivDown(collateralPrice, ORACLE_PRICE_SCALE).wMulDown(lltv);

with ORACLE_PRICE_SCALE = 1e36. You can see the same conversion pattern in liquidation too:

solidity
uint256 seizedAssetsQuoted = seizedAssets.mulDivUp(collateralPrice, ORACLE_PRICE_SCALE);

When the collateral or loan token is a vault share#

Because Morpho can use ERC4626 vault shares as either collateral or loan token.

Example: a collateral token might be an ERC4626 vault share token like sDAI, or a stablecoin yield vault share. In that case, the oracle must incorporate the conversion shares → underlying assets, because the external price feeds are usually expressed in terms of the underlying asset, not in “shares”.

ERC4626 convertToAssets conversion inside the Morpho oracle price path

That is exactly what VaultLib.getAssets does:

solidity
library VaultLib {
    /// @dev Converts `shares` into the corresponding assets on the `vault`.
    /// @dev When `vault` is the address zero, returns 1.
    function getAssets(IERC4626 vault, uint256 shares) internal view returns (uint256) {
        if (address(vault) == address(0)) return 1;

        return vault.convertToAssets(shares);
    }
}

So the following code:

solidity
BASE_VAULT.getAssets(BASE_VAULT_CONVERSION_SAMPLE)

means “how many underlying base-assets correspond to BASE_VAULT_CONVERSION_SAMPLE shares?”.

Here BASE_VAULT_CONVERSION_SAMPLE is typically just 1e18 as shown in the test case in MorphoChainlinkOracleV2FactoryTest.sol:

solidity
        IMorphoChainlinkOracleV2 oracle = factory.createMorphoChainlinkOracleV2(
            sDaiVault, 1e18, daiEthFeed, feedZero, 18, vaultZero, 1, usdcEthFeed, feedZero, 6, salt
        );

Same for the quote side. When there is no vault, the factor is 1 and disappears.

Put a unit on every feed#

The base is what the borrower posts. The quote is what they owe. A provider may label a feed “ETH/USD”. Its answer is measured in USD per ETH. Use those words when multiplying. For LINK collateral and a DAI loan, suppose the first two feeds report ETH per LINK and USD per ETH, and the quote feed reports USD per DAI. Then

(ETH/LINK)(USD/ETH)USD/DAI=DAILINK.\frac{(\mathrm{ETH}/\mathrm{LINK})(\mathrm{USD}/\mathrm{ETH})}{\mathrm{USD}/\mathrm{DAI}}=\frac{\mathrm{DAI}}{\mathrm{LINK}}.

The intermediate ETH and USD units cancel. An unused second quote feed has address zero and contributes 1. If there is a single feed that already reports DAI per LINK, it can supply the whole base leg with the other feeds omitted. If collateral consists of vault shares, multiply the base leg by the underlying assets per share. The contract evaluates those conversions with configured integer samples on each leg.

The two feed slots on each side support a direct pair or a pair routed through an intermediate asset. The two legs must meet in the same denomination. If a quote-side feed reports USD per USDC, dividing by its answer converts a USD valuation into USDC. That tells us which way the result should move if the stablecoin’s dollar price changes. MorphoChainlinkOracleV2 and its constructor

Where the scale factor comes from#

SCALE_FACTOR is a precomputed constant that makes the returned integer have the right meaning and scaling.

At runtime, the oracle multiplies:

  • vault conversions (in token smallest units), and
  • Chainlink feed answers (which are integers scaled by the feed’s decimals()),

then divides base by quote.

But Morpho expects the oracle output (quoted in loan token Q1Q_1 per collateral token B1B_1) to be scaled by 103610^{36}.

The constructor comment in MorphoChainlinkOracleV2.sol does the derivation in the general 2-hop case. Using the exact same symbols:

  • Assets: B1,B2,Q1,Q2,CB_1, B_2, Q_1, Q_2, C with decimals dB1,dB2,dQ1,dQ2,dCd_{B1}, d_{B2}, d_{Q1}, d_{Q2}, d_C.
  • Base prices: pB1,pB2pB1, pB2.
  • Quote prices: pQ1,pQ2pQ1, pQ2.

First, convert each hop into “per-1-asset” form by applying decimal shifts, then multiply along each path. Morpho’s target is:

price()=1036⋅(pB1⋅10dB2−dB1)⋅(pB2⋅10dC−dB2)(pQ1⋅10dQ2−dQ1)⋅(pQ2⋅10dC−dQ2)\mathtt{price()} = 10^{36}\cdot \frac{(pB1\cdot 10^{d_{B2}-d_{B1}})\cdot(pB2\cdot 10^{d_C-d_{B2}})}{(pQ1\cdot 10^{d_{Q2}-d_{Q1}})\cdot(pQ2\cdot 10^{d_C-d_{Q2}})}

Then simplify the exponent terms (this is exactly the step shown in the Solidity comment):

price()=1036⋅pB1⋅10−dB1⋅pB2pQ1⋅10−dQ1⋅pQ2\mathtt{price()} = 10^{36}\cdot \frac{pB1\cdot 10^{-d_{B1}}\cdot pB2}{pQ1\cdot 10^{-d_{Q1}}\cdot pQ2}

Now connect that target to what the contract computes at runtime.

Let fpB1,fpB2,fpQ1,fpQ2fp_{B1}, fp_{B2}, fp_{Q1}, fp_{Q2} be the feed precisions (i.e. feed.decimals()), so the feeds return:

feed values=pB1⋅10fpB1,  pB2⋅10fpB2,  pQ1⋅10fpQ1,  pQ2⋅10fpQ2\text{feed values} = pB1\cdot 10^{fp_{B1}},\; pB2\cdot 10^{fp_{B2}},\; pQ1\cdot 10^{fp_{Q1}},\; pQ2\cdot 10^{fp_{Q2}}

Ignoring vaults for one line, the runtime structure is:

price()=(pB1⋅10fpB1)⋅(pB2⋅10fpB2)⋅SCALE_FACTOR(pQ1⋅10fpQ1)⋅(pQ2⋅10fpQ2)\mathtt{price()} = \frac{(pB1\cdot 10^{fp_{B1}})\cdot(pB2\cdot 10^{fp_{B2}})\cdot \mathtt{SCALE\_FACTOR}}{(pQ1\cdot 10^{fp_{Q1}})\cdot(pQ2\cdot 10^{fp_{Q2}})}

So SCALE_FACTOR is chosen such that this equals the target 1036⋅pB1⋅10−dB1⋅pB2pQ1⋅10−dQ1⋅pQ210^{36}\cdot \frac{pB1\cdot 10^{-d_{B1}}\cdot pB2}{pQ1\cdot 10^{-d_{Q1}}\cdot pQ2}.

Solving for it (again, exactly matching the Solidity comment) gives:

SCALE_FACTOR=1036⋅10−dB1⋅10dQ1⋅10−fpB1⋅10−fpB2⋅10fpQ1⋅10fpQ2\mathtt{SCALE\_FACTOR} = 10^{36}\cdot 10^{-d_{B1}}\cdot 10^{d_{Q1}}\cdot 10^{-fp_{B1}}\cdot 10^{-fp_{B2}}\cdot 10^{fp_{Q1}}\cdot 10^{fp_{Q2}}

Finally, incorporate the vault conversion samples.

At runtime the numerator contains the assets obtained from the base sample and the denominator contains the assets obtained from the quote sample. To normalize those two samples, the constructor multiplies the scale factor by the following ratio.

sQsB=QUOTE_VAULT_CONVERSION_SAMPLEBASE_VAULT_CONVERSION_SAMPLE\frac{s_Q}{s_B} = \frac{\texttt{QUOTE\_VAULT\_CONVERSION\_SAMPLE}}{\texttt{BASE\_VAULT\_CONVERSION\_SAMPLE}}

Putting everything together yields the compact exponent form used in the article and reflected in code:

SCALE_FACTOR=10  36+dQ1+fpQ1+fpQ2−dB1−fpB1−fpB2⋅sQsB\mathtt{SCALE\_FACTOR} = 10^{\;36 + d_{Q1} + fp_{Q1} + fp_{Q2} - d_{B1} - fp_{B1} - fp_{B2}} \cdot \frac{s_Q}{s_B}

And the code implements exactly that:

solidity
SCALE_FACTOR = 10 ** (
    36
    + quoteTokenDecimals
    + quoteFeed1.getDecimals()
    + quoteFeed2.getDecimals()
    - baseTokenDecimals
    - baseFeed1.getDecimals()
    - baseFeed2.getDecimals()
) * quoteVaultConversionSample / baseVaultConversionSample;

An end-to-end example: wstETH collateral, USDC loan#

In this example we configure the oracle so that it returns wstETH price (as collateral token) quoted in USDC (as loan token). Then Morpho converts collateral to loan units as:

loanAmount=⌊collateralAmount⋅price()1036⌋\text{loanAmount} = \Big\lfloor \frac{\text{collateralAmount}\cdot \texttt{price()}}{10^{36}} \Big\rfloor

Step 1 — Choose feeds so units cancel to USDC/wstETH#

Pick USD as the common denomination. The base feeds report ETH per wstETH and USD per ETH. The quote feed reports USD per USDC. Leave the second quote feed empty. The feed labels in the configuration are wstETH/ETH, ETH/USD and USDC/USD respectively. Their answer units give

(ETH/wstETH)(USD/ETH)USD/USDC=USDC/wstETH.\frac{(\mathrm{ETH}/\mathrm{wstETH})(\mathrm{USD}/\mathrm{ETH})}{\mathrm{USD}/\mathrm{USDC}}=\mathrm{USDC}/\mathrm{wstETH}.

Assume no vault shares here, then:

  • BASE_VAULT = QUOTE_VAULT = address(0)
  • BASE_VAULT_CONVERSION_SAMPLE = QUOTE_VAULT_CONVERSION_SAMPLE = 1

Step 2 — Plug in decimals#

  • Token decimals:
    • baseTokenDecimals = 18 (wstETH)
    • quoteTokenDecimals = 6 (USDC)
  • Feed decimals (typical values; always read them from the feed):
    • wstETH/ETH: 18
    • ETH/USD: 8
    • USDC/USD: 8
    • any address(0) feed has 0 decimals by definition (getDecimals returns 0)

So the constructor exponent becomes:

36+6+8+0−18−18−8=636 + 6 + 8 + 0 - 18 - 18 - 8 = 6

Therefore SCALE_FACTOR = 10^6 (since vault samples are both 1).

Step 3 — Do a numeric sanity check#

Suppose the market is roughly:

  • 1 wstETH≈1.03 ETH1\ \text{wstETH} \approx 1.03\ \text{ETH}
  • 1 ETH≈3000 USD1\ \text{ETH} \approx 3000\ \text{USD}
  • 1 USDC≈1 USD1\ \text{USDC} \approx 1\ \text{USD}

In feed terms (i.e., scaled by feed decimals), that’s roughly:

  • wstETH/ETH: getPrice() ≈1.03×1018\approx 1.03 \times 10^{18}
  • ETH/USD: getPrice() ≈3000×108\approx 3000 \times 10^{8}
  • USDC/USD: getPrice() ≈1×108\approx 1 \times 10^{8}

Then the oracle’s runtime computation is:

price()=⌊106⋅(1.03⋅1018)⋅(3000⋅108)(1⋅108)⌋=3090⋅1024\texttt{price()} = \Big\lfloor 10^6\cdot \frac{(1.03\cdot 10^{18})\cdot(3000\cdot 10^{8})}{(1\cdot 10^{8})} \Big\rfloor = 3090\cdot 10^{24}

Now validate the Morpho-side conversion on exactly 1 wstETH (which is 101810^{18} smallest units):

⌊1018⋅(3090⋅1024)1036⌋=3090⋅106\Big\lfloor \frac{10^{18}\cdot (3090\cdot 10^{24})}{10^{36}} \Big\rfloor = 3090\cdot 10^{6}

That equals 3090 USDC in USDC smallest units (10610^6), which matches the intuitive spot price.

Change only the quote feed to 0.98 USD per USDC while wstETH is still worth 3,090 USD. It now takes more USDC to express the same collateral value. After rounding down to six decimals, one wstETH converts to 3,153.061224 USDC. A calculation that makes the USDC amount fall has inverted the quote leg.

Worth sharing?

Send this analysis to another reviewer.

Share on X