Skip to content
Business logic Audit finding Advanced

Supply interest is earned on `accruedToTreasuryShares` resulting in higher than expected treasury fees and under rare circumstances DOSed pool withdrawals

The treasury's accrued fees are stored as shares and earn supply interest, so the treasury eventually claims more than the intended reserve factor. Under frequent index updates, the treasury's claim can exceed available liquidity, preventing suppliers from withdrawing.

0xAlix2 Follow with A2-security, Bigsam and 3 others

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-06-new-scope-judging/issues/430

Found by

0xAlix2, A2-security, Bigsam, Nihavent, Ocean_Sky, trachev

Summary

Fees on debt interest are calculated in 'assets', but not claimed immediately and stored as shares. When they're claimed, they're treated as regular supplyShares and converted back to assets based on the liquidityIndex at the time they're claimed. This results in the realized fees being higher than expected, and under an extreme scenario may not leave enough liquidity for regular pool suppliers to withdraw their funds.

Root Cause

Each time a pool's reserve state is updated, ReserveLogic::_accrueToTreasury() is called. This function incriments _reserve.accruedToTreasuryShares by the shares equiavalent of the assets taken as a fee. Note vars.amountToMint is in assets, and _reserve.accruedToTreasuryShares is stored in shares as the 'fee assets' are not always immediately sent to the treasury.

JavaScript
  function _accrueToTreasury(uint256 reserveFactor, DataTypes.ReserveData storage _reserve, DataTypes.ReserveCache memory _cache) internal {
    ... SKIP!...

    vars.amountToMint = vars.totalDebtAccrued.percentMul(reserveFactor); // Assets

@>  if (vars.amountToMint != 0) _reserve.accruedToTreasuryShares += vars.amountToMint.rayDiv(_cache.nextLiquidityIndex).toUint128(); // Shares
  }

When any pool withdrawal is executed, PoolLogic::executeMintToTreasury() is called. The stored shares are converted back to assets based on the current liquidityIndex:

JavaScript
  function executeMintToTreasury(
    DataTypes.ReserveSupplies storage totalSupply,
    mapping(address => DataTypes.ReserveData) storage reservesData,
    address treasury,
    address asset
  ) external {
    DataTypes.ReserveData storage reserve = reservesData[asset];

    uint256 accruedToTreasuryShares = reserve.accruedToTreasuryShares;

    if (accruedToTreasuryShares != 0) {
      reserve.accruedToTreasuryShares = 0;
      uint256 normalizedIncome = reserve.getNormalizedIncome();
      uint256 amountToMint = accruedToTreasuryShares.rayMul(normalizedIncome); // Assets, scaled up by current liquidityIndex

      IERC20(asset).safeTransfer(treasury, amountToMint);
      totalSupply.supplyShares -= accruedToTreasuryShares;

      emit PoolEventsLib.MintedToTreasury(asset, amountToMint);
    }
  }

As a result, the actual fee taken by the treasury exceeds the original x% intended by reserveFactor at the time the debt was repaid.

In addition, the accumulation of interest on these accruedToTreasuryShares can lead to pool withdrawals being DOSed under circumstances where the _updateIndexes() is called close to every second to create a compounding effect. This compounding effect on brings the liquidityIndex closer to the borrowIndex. This results in the interest earned on accruedToTreasuryShares causing the pool to run out of liquidity when suppliers withdraw.

Internal pre-conditions

Impact 1

  1. A pool has a non-zero reserveFactor
  2. Pool operates normally with supplies/borrows/repays

Impact 2

  1. A pool has a non-zero reserveFactor
  2. Pool operates normally with supplies/borrows/repays
  3. _updateIndexes() is called each second (or close to)

External pre-conditions

No response

Attack Path

Impact 2

  1. User1 supplies to a pool
  2. User2 borrows from the same pool
  3. As time elapses, _updateIndexes() is called close to every second, bringing liquidityIndex closer to borrowIndex. Note this is callable from an external function Pool::forceUpdateReserves()
  4. User2 repays their borrow including interest
  5. Repeat step 3 just for a few seconds
  6. User1 attempts to withdraw their balance but due to the accrued interest on accruedToTreasuryShares, the pool runs out of liquidity DOSing the withdrawal.

Impact

  1. Generally speaking, in all pools the treasury will end up taking a larger fee than what was set in reserveFactor. That is, if reserveFactor is 1e3 (10%) and 1e18 interest is earned, the protocol will eventually claim more than 10% * 1e18 assets.
  2. Under a specific scenario where _updateIndexes() is called every second, there will not be enough liquidity for suppliers to withdraw because the treasury earning supply interest on their accruedToTreasuryShares is not accounted for.

PoC

The below coded POC implements the 'Attack Path' described above.

First, add this line to the CorePoolTests::_setUpCorePool() function to create a scenario with a non-zero reserve factor:

Diff
  function _setUpCorePool() internal {
    poolImplementation = new Pool();

    poolFactory = new PoolFactory(address(poolImplementation));
+   poolFactory.setReserveFactor(1e3); // 10%
    configurator = new PoolConfigurator(address(poolFactory));

    ... SKIP!...
  }

Then, create a new file on /test/forge/core/pool and paste the below contents.

JavaScript
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import {console2} from 'forge-std/src/Test.sol';
import {PoolLiquidationTest} from './PoolLiquidationTests.t.sol';

contract AuditHighSupplyRateDosWithdrawals is PoolLiquidationTest {

function test_POC_DosedWithdrawalsDueToTreasurySharesAccruing() public {
    uint256 aliceMintAmount = 10_000e18;
    uint256 bobMintAmount = 10_000e18;
    uint256 supplyAmount = 1000e18;
    uint256 borrowAmount = 1000e18;

    _mintAndApprove(alice, tokenA, aliceMintAmount, address(pool));         // alice collateral
    _mintAndApprove(bob, tokenB, bobMintAmount, address(pool));             // bob supply
    _mintAndApprove(alice, tokenB, aliceMintAmount, address(pool));         // alice needs some funds to pay interest

    vm.startPrank(bob);
    pool.supplySimple(address(tokenB), bob, supplyAmount, 0); 
    vm.stopPrank();

    vm.startPrank(alice);
    pool.supplySimple(address(tokenA), alice, aliceMintAmount, 0);  // alice collateral
    pool.borrowSimple(address(tokenB), alice, borrowAmount, 0);     // 100% utilization
    vm.stopPrank();

    for(uint256 i = 0; i < (12 * 60 * 60); i++) { // Each second `_updateIndexes()` is called via external function `forceUpdateReserves()`
        vm.warp(block.timestamp + 1);
        pool.forceUpdateReserves();
    }

    // Alice full repay
    vm.startPrank(alice);
    tokenB.approve(address(pool), type(uint256).max);
    pool.repaySimple(address(tokenB), type(uint256).max, 0);
    uint256 post_aliceTokenBBalance = tokenB.balanceOf(alice);
    uint256 interestRepaidByAlice = aliceMintAmount - post_aliceTokenBBalance;

    for(uint256 i = 0; i < (60); i++) { // warp after for treasury to accrue interest on their 'fee shares' 
        vm.warp(block.timestamp + 1);
        pool.forceUpdateReserves();
    }

    // Check debt has been repaid
    (, , , uint256 debtShares) = pool.marketBalances(address(tokenB));
    assert(debtShares == 0); // All debt has been repaid

    // Treasury assets to claim
    uint256 treasuryAssetsToClaim = pool.getReserveData(address(tokenB)).accruedToTreasuryShares * pool.getReserveData(address(tokenB)).liquidityIndex / 1e27;

    // Bob's assets to claim
    bytes32 bobPos = keccak256(abi.encodePacked(bob, 'index', uint256(0)));
    uint256 bobsAssets = pool.supplyShares(address(tokenB), bobPos) * pool.getReserveData(address(tokenB)).liquidityIndex / 1e27;

    // Impact 1: the interest claimable by the treasury is greater than 10% of the interest repaid
    assert(treasuryAssetsToClaim > pool.factory().reserveFactor() * interestRepaidByAlice / 1e4);

    // Impact 2: Bob & the treasury's claim on the assets is greater than available assets, despite no outstanding debt. 
    // This assert demonstrates that bob's withdrawal would be DOSed as withdrawal calls include a transfer of treasury assets.
    // The withdrawal DOS cannot be shown due to the call reverting due to the 'share underflow' issue described in another report
    uint256 poolLiquidity = tokenB.balanceOf(address(pool));
    assert(bobsAssets + treasuryAssetsToClaim > poolLiquidity); 
  }
}

Mitigation

Three possible solutions:

  1. Immediately send the 'fee assets' to treasury rather than accruing them over time
  2. Store the 'fee assets' in assets instead of shares. This will correctly capture the amount of fee that is intended by reserveFactor. For example if a fee is 10%, the protocol will take exactly 10% of the interest earned on debt.
  3. Account for the creation of new supplyShares by diluting the liquidityIndex upon creating these shares. This solution will allow the conversion back to assets in executeMintToTreasury() to remain unchanged.
    • Note I acknowledge that the calculation of liquidityRate does account for reserveFactor, however given this is out of scope I did not focus on it. Regardless, it does not scale the rate down enough to account for the interest the treasury will earn on these shares.

Discussion

sherlock-admin2

1 comment(s) were left on this issue during the judging contest.

Honour commented:

Invalid: fees can accrue interest as well as is done in AAVE

Honour-d-dev

Escalate

This issue is invalid and is different from the #16 #220 #267 #317 group #240 is not in the above group

accruedToTreasuryShares should earn supply interest, it is accounted for in the interest calculations and is the exact same way aave works as well.

sherlock-admin3

Escalate

This issue is invalid and is different from the #16 #220 #267 #317 group #240 is not in the above group

accruedToTreasuryShares should earn supply interest, it is accounted for in the interest calculations and is the exact same way aave works as well.

You've created a valid escalation!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

Nihavent

Escalate

This issue is invalid and is different from the #16 #220 #267 #317 group #240 is not in the above group

accruedToTreasuryShares should earn supply interest, it is accounted for in the interest calculations and is the exact same way aave works as well.

This report focuses on the edge case regarding frequent calls of \_updateIndexes() however it still demonstrates a withdrawal DOSed due to insufficient liquidity (see impact 2 on the POC and associated comment):

Excerpt from POC:

JavaScript
    ... 

    // Impact 2: Bob & the treasury's claim on the assets is greater than available assets, despite no outstanding debt. 
    // This assert demonstrates that bob's withdrawal would be DOSed as withdrawal calls include a transfer of treasury assets.
    // The withdrawal DOS cannot be shown due to the call reverting due to the 'share underflow' issue described in another report
    uint256 poolLiquidity = tokenB.balanceOf(address(pool));
    assert(bobsAssets + treasuryAssetsToClaim > poolLiquidity); 

If you have any doubt that this is due to the transfer of assets to treasury, you could add the following assert statement showing sufficient liquidity to withdraw if we remove the treasury asset transfer:

Diff
    ...

    // Impact 2: Bob & the treasury's claim on the assets is greater than available assets, despite no outstanding debt. 
    // This assert demonstrates that bob's withdrawal would be DOSed as withdrawal calls include a transfer of treasury assets.
    // The withdrawal DOS cannot be shown due to the call reverting due to the 'share underflow' issue described in another report
    uint256 poolLiquidity = tokenB.balanceOf(address(pool));
    assert(bobsAssets + treasuryAssetsToClaim > poolLiquidity); 
+   assert(bobsAssets <= poolLiquidity);

<ins>This is exactly the same root cause as the family of issues you listed, thus they should remain grouped.</ins> My understanding is in Sherlock duplication rules, valid duplicates do not need to identify the primary attack path.

This report also discusses interest accruing on minted treasury shares results in more than the reserveFactor being claimed by the treasury (see impact 1 in the POC). As mentioned in the mitigations, this could be fixed by sending the fees in assets to the treasury upon debt repayment instead of minting the treasury shares which accrue over time. If this change was implemented it would also mitigate the DOSed withdrawals because a withdrawal would not revert when the pool has just enough liquidity to service the withdrawn assets.

Finally, the point you make about AAVE accruing interest on treasury shares is not directly applicable to Zerolend because AAVE have removed executeMintToTreasury() from the pool withdraw flow shown here and here. As a result, AAVEE need not worry about treasury fees being stored in shares because they won't DOS withdrawals.

EDIT: for clarity I do conceed that impact 1 of this report by itself is low/info severity. But the fix for impact 1 also fixes DOSed withdrawals so it's closely related to impact 2 which is medium severity and matches the grouped family.

cvetanovv

I agree with @Nihavent comment that this issue can remain a duplicate with the others because it has caught the root cause, which the other issues have reported, and the second impact is the same as the other issues(withdrawal DoS).

Also, from the escalation, I agree that #240 does not belong in this group but in the #101 group.

Planning to reject the escalation of this issue(#430) to be invalid, but I'll duplicate #240 with #101.

0xSpearmint

@cvetanovv This issue is invalid.

The root cause of this issue as described by the watsons is that executeMintToTreasury will revert when a user attempts to withdraw all the liquidity from a pool.

This is intended, consider the following scenario that assumes a 10% reserve factor:

  1. Lender lends 10 ETH
  2. Borrower borrows 10 ETH
  3. Later the borrower repays 5 ETH + 1 ETH interest (0.1ETH belongs to the treasury)
  4. Currently there is 6 ETH in the pool, If the lender attempts to withdraw 6 ETH it will revert which is intended because 0.1 ETH belongs to the treasury
  5. The lender can withdraw 5.9 ETH and have no issues

While the 0.1 ETH is in the pool, it is not available liquidity for lenders to withdraw. It is reserved for the treasury

Nihavent

”4. Currently there is 6 ETH in the pool, If the lender attempts to withdraw 6 ETH it will revert which is intended because 0.1 ETH belongs to the treasury”

In this example the lender has supply shares equal in value to 10.9 ETH, why should a withdrawal of 6 ETH revert when the pool has 6 ETH of liquidity? Yes the treasury holds supply shares equal to 0.1 ETH. These supplyShares are the same as any other supplyShares and should not need to be provisioned for in every single withdrawal.

What if treasuryShares are worth 2 ETH, a pool has 3 ETH of liquidity and a user who holds supplyShares worth 2 ETH attempts to withdraw 2 ETH. Why should this revert?

”The root cause of this issue as described by the watsons is that executeMintToTreasury will revert when a user attempts to withdraw all the liquidity from a pool.”

Not necessarily, the example I just gave shows a user attempting to withdraw less than all the liquidity available and still facing a revert.

Note that Aave fixed this issue by removing ‘executeMintToTreasury’ from the withdrawal flow as I described here

0xjuaan

The pool has 6 ETH worth of liquidity, but 0.1 ETH is reserved for the treasury. Due to the reserve factor of 10%. Clearly these funds meant for the treasury should not be withdrawable by lenders.

Nihavent

” Clearly these funds meant for the treasury should not be withdrawable by lenders.”

It is completely misleading to suggest that lenders are trying to withdraw treasury funds. They’re only trying to withdraw <ins>their funds</ins>.

The issue is clearly visible in pools with low liquidity and accumulating treasury fees such as this example:

” What if treasuryShares are worth 2 ETH, a pool has 3 ETH of liquidity and a user who holds supplyShares worth 2 ETH attempts to withdraw 2 ETH.”

Where a withdrawal of any amount exceeding 1 ETH is DOSed until a repayment/deposit is made that covers the withdrawal amount and all treasury fees (which continue to accumulate). Note if the asset value of the treasury shares exceeds the available liquidity in the pool all withdrawals are DOSed.

It seems like you’re making the variable name ‘reserveFactor’ do too much work. If these funds were truly intended to be reserved, they would not be borrowable.

This issue was fixed in Aave for a reason, I’m yet to see a compelling argument why it’s not an issue in Zerolend

cvetanovv

I believe this issue and its duplicates (excluding #240) are valid because the accumulation of treasury fees could ultimately result in a situation where all withdrawals from the pool are DOSed.

This occurs when the total accrued treasury fees exceed the available liquidity in the pool, thereby preventing suppliers from withdrawing their assets until the pool is replenished.

As @Nihavent has pointed out, Aave resolved this issue by excluding ‘executeMintToTreasury’ from the withdrawal flow.

My previous decision to reject escalation remains. I will only invalidate #240

0xSpearmint

@cvetanovv The treasury fees is 10% of the interest paid on loans. This is orders of magnitude smaller than the principal liquidity of the pool. It is not realistic at all for the treasury fees to exceed the available liquidity in the pool unless the pool has > 99% utilization so there is barely anything left. This edge case will not last long at all since the borrower will have a huge interest rate to pay so the DOS will be well below 7 days and the lenders will receive huge yield for that period.

Furthermore every time a single successful withdrawal occurs, the treasury fees reset to 0. This makes it even harder to accumulate an amount to cause a DOS.

Nihavent

"It is not realistic at all for the treasury fees to exceed the available liquidity in the pool unless the pool has > 99% utilization so there is barely anything left. This edge case will not last long at all since the borrower will have a huge interest rate to pay so the DOS will be well below 7 days and the lenders will receive huge yield for that period."

Your comment is making a lot of assumptions given high utilization is a completely valid pool state. There are a variety of IRMs and varying incentives for users.

  • There may be pools using DefaultInterestRateStrategy where the 'debtSlope' settings are not high enough. In these pools, the utilization has minimal impact on rates and users have little incentive to repay quickly.
  • Even if this isn't the case, higher utilization results in more interest repaid which results in more treasury fees which further increases the minimum deposit or repayment required to un-dos withdrawals.
  • Not all IRMs increase rates as a function of utilization, we can see the codebase has plans for a FixedInterestRateStrategy. Your comment gives no consideration to extended DOS in pools with fixed rate stratergies.

"Furthermore every time a single successful withdrawal occurs, the treasury fees reset to 0. This makes it even harder to accumulate an amount to cause a DOS."

The issue is no withdrawal can occur when accumulated treasury shares exceed pool liquidity.

cvetanovv

I agree with @Nihavent comment, and my previous decision remains: https://github.com/sherlock-audit/2024-06-new-scope-judging/issues/430#issuecomment-2435074872

WangSecurity

Result: Medium Has duplicates

sherlock-admin4

Escalations have been resolved successfully!

Escalation status:

The original report as published on Sherlock, by 0xAlix2. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

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 treasury fee is stored as supply shares rather than assets, so it earns supply interest and is converted back to assets at a later, higher index.

Impact

The treasury could claim more than the configured reserve factor, and in a specific scenario with frequent index updates, suppliers may be unable to withdraw due to insufficient liquidity.

What the attacker needed

Pool has non-zero reserve factor; pool has supplies and borrows; indexes updated almost every second

The fix

The fee should be sent to the treasury immediately in assets, or stored in assets rather than shares, or the liquidity index should be diluted when creating the shares.

How it was found

  1. A user supplies tokens to a pool with a non-zero reserve factor.
  2. Another user borrows from the same pool.
  3. The reserve indexes are updated almost every second via an external function.
  4. The borrower repays the loan including interest.
  5. The indexes are updated for a few more seconds so the treasury shares accrue interest.
  6. The supplier tries to withdraw but the pool lacks liquidity because the treasury's claim has grown.

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 borrowers pay interest, a slice goes to the protocol's treasury. Instead of paying it out immediately, the code records it as a share of the pool, like a normal depositor's balance. Because shares grow in value over time, the treasury ends up with more than the intended cut, and in extreme cases the pool may not have enough free funds for ordinary depositors to withdraw.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by 0xAlix2

View all

39 more disclosed reports, best first.

More from ZeroLend One

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.