Skip to content
Business logic Audit finding Intermediate

Because of the asset: Share 1:1 Conversion , if vault incurs a loss, the last user to withdraw will take the entire loss

The vault converts deposits and withdrawals at a fixed 1:1 rate even after a loss reduces its assets, so the last user to withdraw cannot receive their full share. An attacker could exploit this by being the last to withdraw, leaving other users to bear the entire loss.

Infect3d Follow with zhaojohnson, Spearmint and 3 others

Originally disclosed on Code4rena

Submitted by Infect3d, also found by zhaojohnson, Spearmint, lian886, pkqs90, and nnez

Because of the 1:1 conversion rate in PoolV3, if the pool incur a loss due to liquidation from borrowed asset through CDPVault, last user to withdraw will take the full loss.

Vulnerability details

Every user should be allowed to withdraw a fair share of what’s is available in the vault. But as:

There will be situations where the last user to withdraw will not be made whole.

Also, if the last user A is not whole, and another user B deposit to the vault, A can get its missing assets from B deposit and B will be at loss waiting for another deposit.

Scenario:

  1. Alice and Bob deposit 10 ETH each to PoolV3, PoolV3 has 20 ETH.
  2. Each user receive 10 shares, and there are 20 total shares.
  3. Eve deposit collateral to CDPVault and borrow 5 ETH.
  4. Eve get liquidated, the loss is 1 ETH.
  5. Treasury has 0 remaining assets to cover the debt (works also if less than 1 ETH treasury).
  6. PoolV3 has now 19 ETH, and Alice and Bob 10 shares each where the exchange rate is 1:1.
  7. Alice withdraw 10 ETH with her 10 shares.
  8. There’s only 9 ETH left for Bob.
File: src/PoolV3.sol
529:     function repayCreditAccount(
530:         uint256 repaidAmount,
531:         uint256 profit,
532:         uint256 loss
533:     )
...:
...: // ------- some code ------- //
...:
548:         if (profit > 0) {
549:             _mint(treasury, convertToShares(profit));
550:         } else if (loss > 0) {                         <@(1) //we're in this case when there's a loss
551:             address treasury_ = treasury;
552:             uint256 sharesInTreasury = balanceOf(treasury_);
553:             uint256 sharesToBurn = convertToShares(loss);
554:❌                if (sharesToBurn > sharesInTreasury) { <@(2) //sharesToBurn are capped to sharesInTreasury
555:                 unchecked {
556:                     emit IncurUncoveredLoss({
557:                         creditManager: msg.sender,
558:                         loss: convertToAssets(sharesToBurn - sharesInTreasury)
559:                     });
560:                 }
561:❌                     sharesToBurn = sharesInTreasury; <@(2)
562:             }
563:❌                _burn(treasury_, sharesToBurn);
564:         }

Impact

Loss of funds for users. Unfair loss distribution among users, as the only last withdrawer will incur the entire loss of the vault

Proof of Concept

Add this test to src/test/unit/CDPVault.t.sol:

     function testAudit_PoolV3LastWithdrawerAtLossWhenBadDebt() public {
        CDPVault vault = createCDPVault(token, 150 ether, 0, 1.25 ether, 1 ether, 1 ether);
        createGaugeAndSetGauge(address(vault));
          liquidityPool.setLock(false);
          // removing the initial deposit made in setUp() so that PooLV3 is empt
          liquidityPool.withdraw(1_000_000 ether, address(this), address(this));

          address alice = makeAddr("alice");
          address bob = makeAddr("bob");
        address position = address(this);

          address poolUnderlying = liquidityPool.underlyingToken();

          // Alice deposits 50 ETH
          deal(poolUnderlying, alice, 50 ether);
          vm.startPrank(alice);
          IERC20(underlyingToken).approve(address(liquidityPool), 50 ether);
          liquidityPool.deposit(50 ether, alice);
          vm.stopPrank();

          // Bob deposits 50 ETH
          deal(poolUnderlying, bob, 50 ether);
          vm.startPrank(bob);
          IERC20(underlyingToken).approve(address(liquidityPool), 50 ether);
          liquidityPool.deposit(50 ether, bob);
          vm.stopPrank();

          // state after liquidation
          console.log("----------  initial state with borrowed assets ----------");
          console.log("PoolV3 shares balance: %e", liquidityPool.totalSupply());
          console.log("PoolV3 ETH balance: %e", IERC20(poolUnderlying).balanceOf(address(liquidityPool)));

          // Simulating a user depositing 100 collateral and borrowing 80 ETH through CDPVault
        _modifyCollateralAndDebt(vault, 100 ether, 80 ether);

        uint256 virtualDebtBefore = virtualDebt(vault, position);
          console.log("virtualDebt before: %e", virtualDebtBefore);

        vm.warp(block.timestamp + 365 days);

        uint256 virtualDebtAfter = virtualDebt(vault, position);
          console.log("virtualDebt after (accrued interest): %e", virtualDebtAfter);

        // Simulating liquidation of the position and bad debt
          uint256 repayAmount = 80 ether;
        _updateSpot(0.7 ether);
        mockWETH.approve(address(vault), repayAmount);
        vault.liquidatePositionBadDebt(position, repayAmount);

          // state after liquidation
          console.log("\r");
          console.log("----------  state after bad debt liquidation ----------");
          console.log("PoolV3 shares balance: %e", liquidityPool.totalSupply());
          console.log("PoolV3 ETH balance: %e", IERC20(poolUnderlying).balanceOf(address(liquidityPool)));
          console.log("... Still 100 shares in PoolV3, but only 90 ETH left for Alice and Bob ...");

          vm.prank(alice);
          liquidityPool.withdraw(50 ether, alice, alice);

          console.log("\r");
          console.log("----------  state after Alice withdraw ----------");
          console.log("PoolV3 shares balance: %e", liquidityPool.totalSupply());
          console.log("PoolV3 ETH balance: %e", IERC20(poolUnderlying).balanceOf(address(liquidityPool)));
          console.log("... Bob has 50 shares but can only withdraw 40 ETH ...");

          vm.prank(bob);
          vm.expectRevert("SafeCast: value must be positive");
          liquidityPool.withdraw(50 ether, bob, bob);
     }

Logs:

Ran 1 test for src/test/unit/CDPVault.t.sol:CDPVaultTest
[PASS] testAudit_collateralDebt() (gas: 3980542)
Logs:
  ----------  initial state with borrowed assets ----------
  PoolV3 shares balance: 1e20
  PoolV3 ETH balance: 1e20
  virtualDebt before: 8e19
  virtualDebt after (accrued interest): 1.03138823529411764705e20

  ----------  state after bad debt liquidation ----------
  PoolV3 shares balance: 1e20
  PoolV3 ETH balance: 9e19
  ... Still 100 shares in PoolV3, but only 90 ETH left for Alice and Bob ...

  ----------  state after Alice withdraw ----------
  PoolV3 shares balance: 5e19
  PoolV3 ETH balance: 4e19
  ... Bob has 50 shares but can only withdraw 40 ETH ...

Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 5.32ms (2.27ms CPU time)

Recommended Mitigation Steps

When there are more shares than assets and vault cannot make all users whole. Withdrawals should be lossy to split loss over all users.

This could be something like this:

    /// @dev Internal conversion function (from assets to shares) with support for rounding direction
    /// @dev Pool is not vulnerable to the inflation attack, so the simplified implementation w/o virtual shares is used
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal returns (uint256 shares) {
        uint256 supply = totalSupply();
          if (supply < totalAssets()) {
               shares = (assets == 0 || supply == 0) ? assets : assets.mulDiv(supply, totalAssets(), rounding);
          }
          else {
               shares = assets;
          }
        return shares;
    }

    /// @dev Internal conversion function (from shares to assets) with support for rounding direction
    /// @dev Pool is not vulnerable to the inflation attack, so the simplified implementation w/o virtual shares is used
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal returns (uint256 assets) {
        uint256 supply = totalSupply();
          if (supply < totalAssets()) {
               assets = (supply == 0) ? shares : shares.mulDiv(totalAssets(), supply, rounding);
          }
          else {
               assets = shares;
          }
        return assets;
    }

Assessed type

Math

0xtj24 (LoopFi) acknowledged

Koolex (judge) decreased severity to Medium


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

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

The vault uses a fixed 1:1 conversion between shares and assets instead of adjusting the exchange rate when the vault's total assets fall below total shares.

Impact

The last user to withdraw loses part or all of their deposit, and the loss is not shared fairly among all users.

What the attacker needed

A user borrows from the vault; the borrower is liquidated at a loss; the treasury cannot cover the loss; a user withdraws before others

The fix

The conversion between shares and assets should account for the vault's actual asset-to-share ratio so that losses are shared proportionally among all users.

How it was found

  1. Alice and Bob each deposit 10 ETH into PoolV3, receiving 10 shares each.
  2. Eve deposits collateral into CDPVault and borrows 5 ETH from the pool.
  3. Eve is liquidated and the pool incurs a 1 ETH loss, with the treasury having no assets to cover it.
  4. The pool now holds 19 ETH but still has 20 shares at a 1:1 rate.
  5. Alice withdraws her 10 shares and receives 10 ETH.
  6. Only 9 ETH remains for Bob, who holds 10 shares.

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.

A vault is a shared pot where people deposit money and get shares. Normally each share is worth the same amount, but here the vault always treats one share as one coin even after some money is lost. So if the pot shrinks, the last person to take their money out gets less than they put in, while earlier people got their full amount.

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 Infect3d

View all

8 more disclosed reports, best first.

More from LoopFi

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.