Skip to content
Business logic Audit finding Advanced

Incorrect accounting bug of the yDUSD vault leads to total loss of depositors’ DUSD assets

The yDUSD vault's total supply (shares) is not updated when the Ditto protocol mints DUSD discount debt directly to the vault, so the vault's total assets increase while total shares remain zero. A user who deposits DUSD afterwards receives zero shares and loses all deposited assets.

serial-coder Follow with d3e4

Originally disclosed on Code4rena

Submitted by serial-coder, also found by d3e4

Summary

The current implementation of the yDUSD vault does not properly support the auto-compounding token rewards mechanism by directly minting the DUSD assets to the vault.

Due to an incorrect accounting bug of the vault’s total supply (shares), depositors can lose some deposited DUSD assets (principal) or even all the assets when the Ditto protocol mints DUSD debts to the vault to account for any discounts.

Description

When the match price is below the oracle price, the OrdersFacet::_matchIsDiscounted() will be invoked to account for a discount by minting the discount (newDebt) (@1 in the snippet below) to the yDUSD vault.

Assuming the yDUSD vault is empty (i.e., both totalAssets and totalSupply are 0), for simplicity’s sake. This step will increase the vault’s total DUSD assets (totalAssets — spot balance) without updating the vault’s total supply (totalSupply — tracked shares).

    function _matchIsDiscounted(MTypes.HandleDiscount memory h) external onlyDiamond {
        ...

        if (pctOfDiscountedDebt > C.DISCOUNT_THRESHOLD && !LibTStore.isForcedBid()) {
            ...

            // @dev Increase global ercDebt to account for the increase debt owed by shorters
            uint104 newDebt = uint104(ercDebtMinusTapp.mul(discountPenaltyFee));
            Asset.ercDebt += newDebt;
            Asset.ercDebtFee += uint88(newDebt); // should be uint104?

            // @dev Mint dUSD to the yDUSD vault for
            // Note: Does not currently handle mutli-asset
@1          IERC20(h.asset).mint(s.yieldVault[h.asset], newDebt);
                //@audit @1 -- When the match price is below the oracle price, the _matchIsDiscounted()
                //             will be invoked to account for a discount by minting the discount (newDebt)
                //             to the yDUSD vault.
                //
                //             Assuming that the yDUSD vault is empty (i.e., totalAssets and totalSupply are 0),
                //             for simplicity's sake.
                //
                //             This step will increase the vault's total DUSD assets (totalAssets -- spot balance)
                //             without updating the vault's total supply (totalSupply -- tracked shares).
        }
    }

After @1, when a user deposits their DUSD assets to the yDUSD vault, the ERC4626::previewDeposit() (@2 in the snippet below) will be executed to calculate the shares based on the deposited assets.

An incorrect accounting bug of the vault’s total supply (tracked shares) occurs in @1 above. In this example, the calculated shares will be 0 since the totalSupply is 0 (if the totalSupply != 0, the calculated shares can be less than expected). For more details, refer to @2.1 below.

Since the calculated shares == 0, the user will receive 0 shares and lose all deposited DUSD assets (@3). Even the slippage protection check (@4) cannot detect the invalid calculation due to the slippage.mul(shares) == 0, and the user’s tracked shares remain unchanged. (Actually, I discovered another issue regarding the slippage protection check, which will be reported separately.)

    function deposit(uint256 assets, address receiver) public override returns (uint256) {
        if (assets > maxDeposit(receiver)) revert Errors.ERC4626DepositMoreThanMax();

        //@audit @2 -- After @1, when a user deposits their DUSD assets to the yDUSD vault, the previewDeposit()
        //             will be executed to calculate the shares based on the deposited assets.
        //
        //             Due to an incorrect accounting bug of the vault's total supply (tracked shares) occurs in @1,
        //             the calculated shares, in this case, will be 0 since totalSupply is 0 (if totalSupply != 0,
        //             the calculated shares can be less than expected). For more details, refer to @2.1.
@2      uint256 shares = previewDeposit(assets);

        uint256 oldBalance = balanceOf(receiver);
        //@audit @3 -- Since the calculated shares == 0, the user will receive 0 shares. Thus, they will lose all
        //             deposited DUSD assets.
@3      _deposit(_msgSender(), receiver, assets, shares);
        uint256 newBalance = balanceOf(receiver);

        // @dev Slippage is likely irrelevant for this. Merely for preventative purposes
        uint256 slippage = 0.01 ether;
@4      if (newBalance < slippage.mul(shares) + oldBalance) revert Errors.ERC4626DepositSlippageExceeded();
            //@audit @4 -- Even the slippage protection check above cannot detect the invalid calculation since
            //             the slippage.mul(shares) == 0, and the user's tracked shares remain unchanged.

        return shares;
    }

To calculate the user’s shares, the ERC4626::previewDeposit() calls the ERC4626::_convertToShares() (@2.1 in the snippet below).

The calculated shares will be 0 (due to the rounding down) (@2.2) because the ERC20::totalSupply() will return 0 (the vault’s tracked total shares) while the ERC4626::totalAssets() will return the previously minted discount amount (i.e., the newDebt from @1). Refer to the @2.2 for a detailed explanation of the calculation.

        // FILE: node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol
        function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
            //@audit @2.1 -- The previewDeposit() calls the _convertToShares() to calculate the shares.
@2.1        return _convertToShares(assets, Math.Rounding.Down);
        }

        // FILE: node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol
        function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
            //@audit @2.2 -- The calculated shares, in this case, will be 0 (due to the rounding down)
            //               because the totalSupply() will return 0 (the vault's tracked total shares)
            //               while the totalAssets() will return the previously minted discount amount
            //               (i.e., the newDebt from @1).
            //
            //                shares = assets * (0 + 10 ** 0) / newDebt
            //                       = assets * 1 / newDebt (e.g., assets < newDebt)
            //                       = 0 (due to rounding down)
@2.2        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
        }

As you can see, the ERC20::totalSupply() returns the vault’s tracked total shares (0) (@2.2.1 in the snippet below), and ERC4626::totalAssets() returns the previously minted discount amount (i.e., the newDebt from @1) (@2.2.2).

        // FILE: node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol
        function totalSupply() public view virtual override returns (uint256) {
            //@audit @2.2.1 -- The totalSupply() returns the vault's tracked total shares (0).
@2.2.1      return _totalSupply; //@audit -- tracked shares
        }

        // FILE: node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol
        function totalAssets() public view virtual override returns (uint256) {
            //@audit @2.2.2 -- The totalAssets() returns the previously minted discount amount
            //                 (i.e., the newDebt from @1).
@2.2.2      return _asset.balanceOf(address(this)); //@audit -- spot balance
        }

Impact

Depositors can lose some deposited DUSD assets (principal) or whole assets when the Ditto protocol mints DUSD debts to the yDUSD vault to account for discounts.

Proof of Concept

This section provides a coded PoC.

Place the test_PoC_yDUSD_Yault_totalSupply_IncorrectInternalAccounting() in the .test/YDUSD.t.sol file and run the test using the command: forge test -vv --mt test_PoC_yDUSD_Yault_totalSupply_IncorrectInternalAccounting.

The PoC shows that a user loses all DUSD assets (both principal and yield) when he deposits the assets into the yDUSD vault right after the protocol has minted debts to the vault.

function test_PoC_yDUSD_Yault_totalSupply_IncorrectInternalAccounting() public {
    // Create discounts to generate newDebt
    uint88 newDebt = uint88(discountSetUp());
    assertEq(rebasingToken.totalAssets(), newDebt);
    assertEq(rebasingToken.totalSupply(), 0);
    assertEq(rebasingToken.balanceOf(receiver), 0);
    assertEq(rebasingToken.balanceOf(_diamond), 0);
    assertEq(rebasingToken.balanceOf(_yDUSD), 0);
    assertEq(token.balanceOf(_yDUSD), newDebt);

    // Receiver deposits DUSD into the vault to get yDUSD
    vm.prank(receiver);
    rebasingToken.deposit(DEFAULT_AMOUNT, receiver);

    assertEq(rebasingToken.totalAssets(), DEFAULT_AMOUNT + newDebt);
    assertEq(rebasingToken.totalSupply(), 0);       // 0 amount due to the invalid accounting bug of totalSupply
    assertEq(rebasingToken.balanceOf(receiver), 0); // 0 amount due to the invalid accounting bug of totalSupply
    assertEq(rebasingToken.balanceOf(_diamond), 0);
    assertEq(rebasingToken.balanceOf(_yDUSD), 0);
    assertEq(token.balanceOf(_yDUSD), DEFAULT_AMOUNT + newDebt);

    // Match at oracle
    fundLimitBidOpt(DEFAULT_PRICE, DEFAULT_AMOUNT, extra);
    fundLimitAskOpt(DEFAULT_PRICE, DEFAULT_AMOUNT, extra);

    skip(C.DISCOUNT_WAIT_TIME);

    // Receiver expects to withdraw yDUSD and get back more DUSD than the original amount (Expect Revert!!!)
    // @dev Roughly DEFAULT_AMOUNT + newDebt, but rounded down
    uint88 withdrawAmountReceiver = 54999999999999999999990;
    vm.prank(receiver);
    vm.expectRevert(Errors.ERC4626WithdrawMoreThanMax.selector); // Expect Revert!!!
    rebasingToken.proposeWithdraw(withdrawAmountReceiver);

    // 0 amount due to the invalid accounting bug of totalSupply
    assertEq(rebasingToken.maxWithdraw(receiver), 0);
}

Recommended Mitigation Steps

Rework the yDUSD vault by applying the concept of a single-sided auto-compounding token rewards mechanism of the xERC4626, which is fully compatible with the ERC4626 and ultimately maintains balances using internal accounting to prevent instantaneous changes in the exchange rate.

@ditto-eth (sponsor) acknowledged

Note: see original submission for full discussion.


The original report as published on Code4rena, by serial-coder. 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

Likely the vault's share accounting is not updated when DUSD is minted directly to it, so totalAssets rises while totalSupply stays zero, causing previewDeposit to round shares down to zero.

Impact

Depositors can lose some or all of their deposited DUSD assets when the protocol mints DUSD debts to the vault to account for discounts.

What the attacker needed

Protocol mints discount debt to the vault; vault has zero total shares; user deposits DUSD into the vault

The fix

The vault should be reworked to use a single-sided auto-compounding rewards mechanism, such as xERC4626, that maintains balances with internal accounting to prevent instantaneous exchange-rate changes.

How it was found

  1. Create discounts so the protocol mints newDebt to the yDUSD vault, making totalAssets equal newDebt and totalSupply zero.
  2. A receiver deposits DUSD into the vault to get yDUSD.
  3. The deposit results in zero shares for the receiver and totalSupply remains zero.
  4. The receiver later tries to withdraw more than the original amount and the transaction reverts with ERC4626WithdrawMoreThanMax.
  5. The receiver's maxWithdraw is zero.

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 lets people deposit tokens and gives them shares representing their portion. Here, the protocol added tokens to the vault without adding any shares, so the vault's balance grew but the share count stayed at zero. When a person then deposited, the maths for how many shares they should get produced zero, so they got nothing back for their tokens.

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 serial-coder

View all

9 more disclosed reports, best first.

More from DittoETH Invitational

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.