Rounding discrepancy between `MorphoLendingRouter::healthFactor` and `Morpho::repay` causes position migration failures
The MorphoLendingRouter::healthFactor function calculates borrowed assets by rounding down, while Morpho's repay function rounds up, causing a 1 wei discrepancy. This leads to insufficient flash loan amounts during position migration, causing the migration to revert.
Source: https://github.com/sherlock-audit/2025-06-notional-exponent-judging/issues/417
Found by
0xRstStn, 0xpiken, Bigsam, Ragnarok, bretzel, mstpr-brainbot, rudhra1749, shiazinho, talfao, touristS, wickie, xiaoming90
Summary
A flaw in how borrow assets are calculated in MorphoLendingRouter::healthFactor causes position migrations to revert under specific conditions. The function underestimates the true debt owed by rounding down, while Morpho internally rounds up for repayment. This discrepancy leads to insufficient asset transfers during AbstractLendingRouter::migratePosition, breaking a core protocol feature.
Although the rounding difference may not appear initially, it inevitably emerges over time as interest accrues and the market grows, causing migrations that once worked to start failing silently, making this a latent but critical bug.
Root Cause
In MorphoLendingRouter::healthFactor, the borrowed assets are calculated using integer division:
MorphoLendingRouter::healthFactor#L279
if (position.borrowShares > 0) {
borrowed = (uint256(position.borrowShares) * uint256(market.totalBorrowAssets)) / uint256(market.totalBorrowShares);
}
However, In Morpho::_isHealthy and Morpho::repay, the equivalent borrow amount is calculated using a rounding-up approach:
uint256 borrowed = uint256(position[id][borrower].borrowShares).toAssetsUp(
market[id].totalBorrowAssets, market[id].totalBorrowShares
);
else assets = shares.toAssetsUp(market[id].totalBorrowAssets, market[id].totalBorrowShares);
The discrepancy causes MorphoLendingRouter::healthFactor to underestimate the amount required to repay a loan, especially by ~1 wei in precision-sensitive scenarios, like AbstractLending::migratePosition.
Internal Pre-conditions
- The user's position must have some borrowed assets.
- No excess asset tokens are held in the new router during migration (which is by design).
External Pre-conditions
Initially, this rounding inconsistency may not manifest. However, as the market accrues interest and grows, the discrepancy between the round-down calculation used by MorphoLendingRouter::healthFactor and the round-up logic used internally by Morpho (e.g. in repay) will inevitably emerge, even for previously safe positions.
Attack Path
migratePositioncallshealthFactoron the previous router, which underestimates the borrow amount.- This amount is used to request a flash loan.
- During
_exitWithRepay, Morpho callsrepay()with the actual borrow shares. repay()requires more assets (rounded-up) than were flash-borrowed.- The internal
safeTransferFromfails due to insufficient balance. - The entire migration reverts.
Check the impact section for more details.
Impact
This bug has a significant impact: it breaks the migratePosition functionality, a core protocol feature designed to allow seamless transitions between lending routers.
The issue stems from an underestimated borrow amount returned by MorphoLendingRouter::healthFactor, due to incorrect rounding (rounding down instead of up). This results in insufficient funds being flash-loaned during a migration, ultimately causing the entire operation to revert.
Here’s a breakdown of how this failure manifests step by step:
- In
AbstractLending::migratePositionthe borrowAmount is obtained from healthFactor (which underestimates the actual borrow due to rounding down):
AbstractLendingRouter::migratePosition#L74
function migratePosition(
address onBehalf,
address vault,
address migrateFrom
) public override isAuthorized(onBehalf, vault) {
if (!ADDRESS_REGISTRY.isLendingRouter(migrateFrom)) revert InvalidLendingRouter();
// Borrow amount is set to the amount of debt owed to the previous lending router
@> (uint256 borrowAmount, /* */, /* */) = ILendingRouter(migrateFrom).healthFactor(onBehalf, vault);
@> _enterPosition(onBehalf, vault, 0, borrowAmount, bytes(""), migrateFrom);
}
_enterPositionpasses the underestimatedborrowAmountinto_flashBorrowAndEnter, which requests a flash loan for that exact amount:
AbstractLendingRouter::_enterPosition#L97
if (borrowAmount > 0) {
_flashBorrowAndEnter(
onBehalf, vault, asset, depositAssetAmount, borrowAmount, depositData, migrateFrom
);
}
- In the
MorphoLendingRouter::onMorphoFlashLoancallback,_enterOrMigrateis called using only the flash loaned amount (no extra funds):
MorphoLendingRouter::onMorphoFlashLoan#L140
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external override {
require(msg.sender == address(MORPHO));
(
address onBehalf,
address vault,
address asset,
uint256 depositAssetAmount,
bytes memory depositData,
address migrateFrom
) = abi.decode(data, (address, address, address, uint256, bytes, address));
@> _enterOrMigrate(onBehalf, vault, asset, assets + depositAssetAmount, depositData, migrateFrom);
// Note: depositAssetAmount here is equal to 0, so we're passing only the asset amount we get from `MorphoLendingRouter::healthFactor`
...
}
- Because this is a migration,
exitPositionis called withassetToRepay = type(uint256).max, signaling a full repayment:
AbstractLendingRouter::_enterOrMigrate#L236
function _enterOrMigrate(
address onBehalf,
address vault,
address asset,
uint256 assetAmount,
bytes memory depositData,
address migrateFrom
) internal returns (uint256 sharesReceived) {
if (migrateFrom != address(0)) {
// Allow the previous lending router to repay the debt from assets held here.
ERC20(asset).checkApprove(migrateFrom, assetAmount);
sharesReceived = ILendingRouter(migrateFrom).balanceOfCollateral(onBehalf, vault);
// Must migrate the entire position
@> ILendingRouter(migrateFrom).exitPosition(
onBehalf, vault, address(this), sharesReceived, type(uint256).max, bytes("")
);
}
...
}
- Inside
_exitWithRepay, the logic switches to using the user'sborrowSharesdirectly to calculate repayment:
MorphoLendingRouter::_exitWithRepay#L192
function _exitWithRepay(
address onBehalf,
address vault,
address asset,
address receiver,
uint256 sharesToRedeem,
uint256 assetToRepay,
bytes calldata redeemData
) internal override {
MarketParams memory m = marketParams(vault, asset);
uint256 sharesToRepay;
@> if (assetToRepay == type(uint256).max) {
// If assetToRepay is uint256.max then get the morpho borrow shares amount to
// get a full exit.
@> sharesToRepay = MORPHO.position(morphoId(m), onBehalf).borrowShares;
@> assetToRepay = 0;
}
bytes memory repayData = abi.encode(
onBehalf, vault, asset, receiver, sharesToRedeem, redeemData, _isMigrate(receiver)
);
// Will trigger a callback to onMorphoRepay
@> MORPHO.repay(m, assetToRepay, sharesToRepay, onBehalf, repayData);
}
- When
Morphoreceives the repay request, it usestoAssetsUp()— rounding up the amount needed to repay the debt.
Morphothen calls back toMorphoLendingRouter::onMorphoRepay, which attempts to transferassetToRepayfrom the receiver:
MorphoLendingRouter::onMorphoRepay#L224
@> function onMorphoRepay(uint256 assetToRepay, bytes calldata data) external override {
require(msg.sender == address(MORPHO));
...
if (isMigrate) {
// When migrating we do not withdraw any assets and we must repay the entire debt
// from the previous lending router.
@> ERC20(asset).safeTransferFrom(receiver, address(this), assetToRepay);
// assetToRepay here is the value passed as parameter from Morpho::repay, rounded-up
assetsWithdrawn = assetToRepay;
}
...
}
This transfer fails because the flash-loaned amount was based on a rounded-down borrow calculation, and is ~1 wei short.
- Since lending routers do not hold idle assets (by design), there are no extra funds available to cover the difference. This causes the
safeTransferFromto revert, breaking the migration flow entirely.
PoC
This proof of concept demonstrates the discrepancy between MorphoLendingRouter::healthFactor and Morpho's internal borrow asset calculation (toAssetsUp). It uses a real, high-liquidity and interest-accruing market, eUSDE/USDE, as an example, to show how the rounding difference manifests in production conditions.
The following test compares the result of:
MorphoLendingRouter::healthFactorround-down calculation (Notional's implementation)- vs Morpho's
toAssetsUp()round-up logic (used during actual repayment).
- Create a file named
POC.solintests/folder. - Add the following code to the newly created file:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Test, console2} from "forge-std/src/Test.sol";
import {MORPHO, Id, IMorphoStaticTyping} from "src/interfaces/Morpho/IMorpho.sol";
contract POC3 is Test {
/// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
uint256 internal constant VIRTUAL_SHARES = 1e6;
/// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
/// empty.
uint256 internal constant VIRTUAL_ASSETS = 1;
// to run this test use --fork-url $RPC_URL
// rpc-url needs to be mainnet
function test_healthFactorReturnsIncorrectBorrowAmountOnChain() public view {
uint256 shares = 100e6;
Id id = Id.wrap(0x140fe48783fe88d2a52b31705577d917628caaf74ff79865b39d4c2aa6c2fd3c);
(,, uint128 totalBorrowAssets, uint128 totalBorrowShares,,) = IMorphoStaticTyping(address(MORPHO)).market(id);
uint256 notionalResult = _calculationNotional(shares, totalBorrowAssets, totalBorrowShares);
uint256 morphoResult = _calculationMorpho(shares, totalBorrowAssets, totalBorrowShares);
console2.log("Protocol borrow amount calculated: ", notionalResult);
console2.log("Needed assets to repay loan by Morpho calculation: ", morphoResult);
assertLt(notionalResult, morphoResult);
}
function test_healthFactorReturnsIncorrectBorrowAmount() public pure {
// 1. User will try to redeem 100e6 shares;
uint256 shares = 100e6;
// Snapshoted values from Morpho market 0x140fe48783fe88d2a52b31705577d917628caaf74ff79865b39d4c2aa6c2fd3c (eUSDE, USDE)
// https://app.morpho.org/ethereum/market/0x140fe48783fe88d2a52b31705577d917628caaf74ff79865b39d4c2aa6c2fd3c/eusde-usde
// 07/16/2025
uint256 totalBorrowAssets = 1683699089027334601033968;
uint256 totalBorrowShares = 1607215221550593809991229062204;
uint256 notionalResult = _calculationNotional(shares, totalBorrowAssets, totalBorrowShares); // Round down to 104
uint256 morphoResult = _calculationMorpho(shares, totalBorrowAssets, totalBorrowShares); // Round up to 105
console2.log("Protocol borrow amount calculated: ", notionalResult);
console2.log("Needed assets to repay loan by Morpho calculation: ", morphoResult);
assertLt(notionalResult, morphoResult);
}
function _calculationMorpho(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
return toAssetsUp(a, b, c);
}
function _calculationNotional(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
return (a * b) / c;
}
/// @dev Calculates the value of `shares` quoted in assets, rounding up.
function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return mulDivUp(shares, totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
/// @dev Returns (`x` * `y`) / `d` rounded up.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
return (x * y + (d - 1)) / d;
}
}
- Run:
forge test --mt test_healthFactorReturnsIncorrectBorrowAmount -vvvv
Output:
Traces:
[18020] POC3::test_healthFactorReturnsIncorrectBorrowAmountOnChain()
├─ [6929] 0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb::market(0x140fe48783fe88d2a52b31705577d917628caaf74ff79865b39d4c2aa6c2fd3c) [staticcall]
│ └─ ← [Return] Market({ totalSupplyAssets: 1948947786194877138152276 [1.948e24], totalSupplyShares: 1870086616999893965690591681848 [1.87e30], totalBorrowAssets: 1682873320105785386589083 [1.682e24], totalBorrowShares: 1606423686119321497595859897438 [1.606e30], lastUpdate: 1752690551 [1.752e9], fee: 0 })
├─ [0] console::log("Protocol borrow amount calculated: ", 104) [staticcall]
│ └─ ← [Stop]
├─ [0] console::log("Needed assets to repay loan by Morpho calculation: ", 105) [staticcall]
│ └─ ← [Stop]
├─ [0] VM::assertLt(104, 105) [staticcall]
│ └─ ← [Return]
└─ ← [Stop]
This 1 wei difference may seem small, but it's sufficient to cause position migration to fail when exact asset repayment is required.
Mitigation
Update MorphoLendingRouter::healthFactor to match Morpho's internal borrow share conversion, using the same rounding-up logic:
borrowed = toAssetsUp(position.borrowShares, market.totalBorrowAssets, market.totalBorrowShares);
Note: don't forget to add virtual asset/share offset constants (e.g., VIRTUAL_ASSETS, VIRTUAL_SHARES).
Discussion
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/notional-finance/notional-v4/pull/8
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the healthFactor function uses integer division that rounds down, while Morpho's repay uses a rounding-up conversion, causing a mismatch in the calculated debt amount.
Impact
This bug breaks the migratePosition functionality, causing migrations to revert due to insufficient funds from the flash loan.
What the attacker needed
User has borrowed assets; No excess tokens in new router
The fix
The protocol team fixed this issue by updating healthFactor to use rounding-up logic matching Morpho's internal conversion.
How it was found
- migratePosition calls healthFactor on the previous router, which underestimates the borrow amount.
- This amount is used to request a flash loan.
- During _exitWithRepay, Morpho calls repay() with the actual borrow shares.
- repay() requires more assets (rounded-up) than were flash-borrowed.
- The internal safeTransferFrom fails due to insufficient balance.
- The entire migration reverts.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
When you borrow assets, the amount you owe can be calculated in two ways: rounding down or rounding up. The protocol used rounding down, but the lending platform used rounding up, so the protocol thought you owed slightly less than you actually did. When trying to move your loan to another platform, it didn't borrow enough to cover the debt, so the transfer failed.