Skip to content
Audit finding Advanced

The `MixOracle.getThePrice` function calculates the price incorrectly using the `TarotOracle.getResult` function as the TWAP price

The MixOracle.getThePrice function uses TarotOracle.getResult as the TWAP price, but that function returns a cumulative value rather than a time-weighted average. This causes the oracle to report a price that is orders of magnitude too high, disrupting the matching of lend and borrow orders and potentially causing user loss of funds.

KupiaSec Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-10-debita-judging/issues/501

Found by

KupiaSec

Summary

The MixOracle.getThePrice function calculates the price using the TarotOracle contract and the pyth oracle. However, it incorrectly uses the TarotOracle.getResult function as the TWAP price, which disrupts the matching mechanism for lend and borrow orders.

Root Cause

In the MixOracle.getThePrice function, the twapPrice112x112 is retrieved from the TarotOracle.getResult function at L50. It then calculates the price of 1 token1 in USD using twapPrice112x112 and the price from the pyth oracle at L65.

Solidity
        ITarotOracle priceFeed = ITarotOracle(_priceFeed);
        address uniswapPair = AttachedUniswapPair[tokenAddress];
        require(isFeedAvailable[uniswapPair], "Price feed not available");
L50:    (uint224 twapPrice112x112, ) = priceFeed.getResult(uniswapPair);
        [...]
        int amountOfAttached = int(
            (((2 ** 112)) * (10 ** decimalsToken1)) / twapPrice112x112
        );
L65:    uint price = (uint(amountOfAttached) * uint(attachedTokenPrice)) /
            (10 ** decimalsToken1);

The TarotOracle.getResult function returns the time-weighted average of reserve0 + price, rather than the TWAP price, from L46. Also, it does not synchronize with uniswapV2Pair.

Solidity
File: contracts\oracles\MixOracle\TarotOracle\TarotPriceOracle.sol
    function getPriceCumulativeCurrent(
        address uniswapV2Pair
    ) internal view returns (uint256 priceCumulative) {
        priceCumulative = IUniswapV2Pair(uniswapV2Pair)
            .reserve0CumulativeLast();
        (
            uint112 reserve0,
            uint112 reserve1,
            uint32 _blockTimestampLast
        ) = IUniswapV2Pair(uniswapV2Pair).getReserves();
        uint224 priceLatest = UQ112x112.encode(reserve1).uqdiv(reserve0);
        uint32 timeElapsed = getBlockTimestamp() - _blockTimestampLast; // overflow is desired
        // * never overflows, and + overflow is desired
L46:    priceCumulative += (uint256(priceLatest) * timeElapsed);
    }

This means that the twapPrice112x112 in the MixOracle.getThePrice function is not the correct TWAP price. Consequently, the DebitaV3Aggregator.matchOffersV3 uses an incorrect price to match lend and borrow orders.

Internal pre-conditions

A user creates the order with MixOracle.

External pre-conditions

  1. None

Attack Path

None

Impact

The incorrect price from the MixOracle disrupts the matching mechanism for lend and borrow orders. This causes user's loss of funds.

PoC

Change the code in the MixOracle.getThePrice function to get the correct price from the uniswapV2Pair.

Diff
File: code\Debita-V3-Contracts\contracts\oracles\MixOracle\MixOracle.sol
-   function getThePrice(address tokenAddress) public returns (int) {
+   function getTotalPrice(address tokenAddress, address uniswapV2Pair) public returns (int, int) {
        // get tarotOracle address
        address _priceFeed = AttachedTarotOracle[tokenAddress];
        require(_priceFeed != address(0), "Price feed not set");
        require(!isPaused, "Contract is paused");
        ITarotOracle priceFeed = ITarotOracle(_priceFeed);

        address uniswapPair = AttachedUniswapPair[tokenAddress];
        require(isFeedAvailable[uniswapPair], "Price feed not available");
        // get twap price from token1 in token0
        (uint224 twapPrice112x112, ) = priceFeed.getResult(uniswapPair);
        address attached = AttachedPricedToken[tokenAddress];

        // Get the price from the pyth contract, no older than 20 minutes
        // get usd price of token0
        int attachedTokenPrice = IPyth(debitaPythOracle).getThePrice(attached);
        uint decimalsToken1 = ERC20(attached).decimals();
        uint decimalsToken0 = ERC20(tokenAddress).decimals();

        // calculate the amount of attached token that is needed to get 1 token1
        int amountOfAttached = int(
            (((2 ** 112)) * (10 ** decimalsToken1)) / twapPrice112x112
        );

        // calculate the price of 1 token1 in usd based on the attached token
        uint price = (uint(amountOfAttached) * uint(attachedTokenPrice)) /
            (10 ** decimalsToken1);

        require(price > 0, "Invalid price");
-       return int(uint(price));
+       uint wftmPrice = IUniswapV2Pair(uniswapV2Pair).current(tokenAddress, 1e18);
+       // uint realPrice = (uint(attachedTokenPrice)) * wftmPrice;
+       uint realPrice = (uint(attachedTokenPrice)) * wftmPrice / (10 ** decimalsToken1);
+       return (int(uint(price)), int(uint(realPrice)));
    }

And add the following testTotalPrice test function in the OracleTarotUSDCEQUAL.t.sol.

Solidity
File: code\Debita-V3-Contracts\test\fork\Loan\ltv\Tarot-Fantom\OracleTarotUSDCEQUAL.t.sol
    function testTotalPrice() public{
        IUniswapV2Pair(EQUALPAIR).sync();
        DebitaMixOracle.setAttachedTarotPriceOracle(EQUALPAIR);
        vm.warp(block.timestamp + 1201);
        IUniswapV2Pair(EQUALPAIR).sync();
        (int originPrice, int realPrice) = DebitaMixOracle.getTotalPrice(EQUAL, EQUALPAIR);
        console.logString(" price:");
        console.logUint(uint(originPrice));
        console.logString("actual price:");
        console.logUint(uint(realPrice));
        console.logString("price diff ratio:");
        console.logUint(uint(originPrice / realPrice));
    }

Use the following command to test above function.

Bash
forge test --rpc-url https://mainnet.base.org --match-path test/fork/Loan/ltv/Tarot-Fantom/OracleTarotUSDCEQUAL.t.sol --match-test testTotalPrice -vvv 

The result is as following:

Text
  mix price:
  147639521176897807
  actual price:
  926069876
  price diff ratio:
  159425897

This indicates that the mix price is 147,639,521,176,897,807, while the actual price is 926,069,876. The mix price is significantly higher than the actual price.

Mitigation

It is recommended to change the code as following:

Diff
File: code\Debita-V3-Contracts\contracts\oracles\MixOracle\MixOracle.sol
    function getThePrice(address tokenAddress) public returns (int) {
-       address _priceFeed = AttachedTarotOracle[tokenAddress];
-       require(_priceFeed != address(0), "Price feed not set");
-       require(!isPaused, "Contract is paused");
-       ITarotOracle priceFeed = ITarotOracle(_priceFeed);
-       address uniswapPair = AttachedUniswapPair[tokenAddress];
-       require(isFeedAvailable[uniswapPair], "Price feed not available");
-       (uint224 twapPrice112x112, ) = priceFeed.getResult(uniswapPair);
+       uint224 twapPrice112x112 = uint224(IUniswapV2Pair(uniswapV2Pair).current(tokenAddress, 1e18));
        address attached = AttachedPricedToken[tokenAddress];

        // Get the price from the pyth contract, no older than 20 minutes
        // get usd price of token0
        int attachedTokenPrice = IPyth(debitaPythOracle).getThePrice(attached);
        uint decimalsToken1 = ERC20(attached).decimals();
        uint decimalsToken0 = ERC20(tokenAddress).decimals();

        // calculate the amount of attached token that is needed to get 1 token1
        int amountOfAttached = int(
            (((2 ** 112)) * (10 ** decimalsToken1)) / twapPrice112x112
        );

        // calculate the price of 1 token1 in usd based on the attached token
        uint price = (uint(amountOfAttached) * uint(attachedTokenPrice)) /
            (10 ** decimalsToken1);

        require(price > 0, "Invalid price");
        return int(uint(price));
    }

Discussion

sherlock-admin2

The protocol team fixed this issue in the following PRs/commits: https://github.com/DebitaFinance/Debita-V3-Contracts/commit/febd7ff204f60af400cd4ff00706da0bb7d47609

The original report as published on Sherlock, by KupiaSec. 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 MixOracle.getThePrice function treats the cumulative price from TarotOracle.getResult as a TWAP price, but getResult returns a cumulative sum that is not synchronised with the Uniswap pair, so the value is not a valid time-weighted average.

Impact

The incorrect price from the MixOracle disrupts the matching mechanism for lend and borrow orders and causes user's loss of funds.

What the attacker needed

A user creates an order using MixOracle

The fix

The protocol team fixed this issue in a commit.

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 price oracle is a service that tells a smart contract the current price of a token. This oracle used a function that returns a running total (a cumulative sum) instead of an average price, so the price it reported was far too high. That wrong price was then used to match borrowers and lenders, which could lead to bad trades and lost money.

More by KupiaSec

View all

28 more disclosed reports, best first.

More from Debita Finance V3

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.