Skip to content
Smart contracts Audit finding Intermediate

MagicLpAggregator doesn’t consider the dcimal of MagicLP

The MagicLpAggregator oracle contract calculates the price of MagicLP shares without accounting for the decimal precision of the MagicLP token, which matches the base token's decimals. When the base token has fewer than 18 decimals, the aggregator returns a price that is inflated by a factor of 10^(18 - baseDecimals), potentially causing incorrect collateral valuation.

ether_sky Follow with hals, DarkTower and 1 other

Originally disclosed on Code4rena

Submitted by ether_sky, also found by hals, DarkTower, and SpicyMeatball

https://github.com/code-423n4/2024-03-abracadabra-money/blob/1f4693fdbf33e9ad28132643e2d6f7635834c6c6/src/mimswap/MagicLP.sol#L163-L165

https://github.com/code-423n4/2024-03-abracadabra-money/blob/1f4693fdbf33e9ad28132643e2d6f7635834c6c6/src/oracles/aggregators/MagicLpAggregator.sol#L37-L46

We can know that the MagicLpAggregator can serve as the price source for MagicLP shares when the prices of base and quote tokens are similar.

MagicLpAggregator would be used to price MagicLP collateral for Cauldrons.
Something to note is that the MagicLP Oracle is only meant for closed-together price pool.
It's just that the oracle is not meant to be used for any kind of MagicLP, just for closely priced tokens like MIM/USDB.

There’s no assurance that we can use MagicLpAggregator for base and quote tokens with only 18 decimals. The MagicLP token has the same decimal as the base token. However, the MagicLpAggregator does not account for this decimal, resulting in incorrect prices when the decimal of the base token is not 18.

Proof of Concept

The MagicLP has the same decimal as the base token.

function decimals() public view override returns (uint8) {
    return IERC20Metadata(_BASE_TOKEN_).decimals();
}

In MagicLpAggregator, we take into account the decimals of the base oracle, quote oracle, base tokens, and quote tokens, but we skip the MagicLP.

function latestAnswer() public view override returns (int256) {
        uint256 baseAnswerNomalized = uint256(baseOracle.latestAnswer()) * (10 ** (WAD - baseOracle.decimals()));
        uint256 quoteAnswerNormalized = uint256(quoteOracle.latestAnswer()) * (10 ** (WAD - quoteOracle.decimals()));
        uint256 minAnswer = baseAnswerNomalized < quoteAnswerNormalized ? baseAnswerNomalized : quoteAnswerNormalized;

        (uint256 baseReserve, uint256 quoteReserve) = _getReserves();
        baseReserve = baseReserve * (10 ** (WAD - baseDecimals));
        quoteReserve = quoteReserve * (10 ** (WAD - quoteDecimals));
        return int256(minAnswer * (baseReserve + quoteReserve) / pair.totalSupply());
}

As a result, the above function will yield an incorrect price when the decimal of the base token is not 18.

Let’s consider an example where the decimal of the base token is 12 and the decimal of the quote token is 18. Additionally, the decimal of the base oracle is 8, and the decimal of the quote oracle is 12. We’ll assume that the price of both tokens is 4 USD. The prices in 18 decimals will be as follows:

base oracle answer           ==>   400000000            (8 decimals)
quote roacle answer          ==>   4000000000000        (12 decimals)
base oracle answer in WAD    ==>   4000000000000000000  (18 decimals)
quote oracle answer in WAD   ==>   4000000000000000000  (18 decimals)

And there are 5 base tokens and 5 quote tokens in the pool. The reserves in 18 decimals will be as follows:

base reserves                ==>   5000000000000        (12 decimals)
quote reserves               ==>   5000000000000000000  (18 decimals)
base reserves in WAD         ==>   5000000000000000000  (18 decimals)
quote reserves in WAD        ==>   5000000000000000000  (18 decimals)

Let’s assume the total share of this pool is 5.

Given that the price of the base and quote tokens is 4 USD, the total value of all tokens will be 40 USD.

total usd                     ==>   40000000 6
total supply                  ==>   5000000000000 12

With 5 shares representing 40 USD, the price of one share should be 8 USD. However, the MagicLpAggregator returns 8,000,000 USD because it did not consider the decimal of MagicLP.

correct answer               ==>   8000000000000000000        (18 decimals)
answer of aggregator         ==>   8000000000000000000000000  (18 decimals)

Add below two mock files into test/mocks.

pragma solidity ^0.8.13;

import {IAggregator} from "interfaces/IAggregator.sol";

contract OracleMock is IAggregator {
  uint8 public decimals_;
  uint8 public price_;

  constructor(uint8 _decimals, uint8 _price) {
    decimals_ = _decimals;
    price_ = _price;
  }

  function decimals() external view override returns (uint8) {
    return decimals_;
  }

  function latestAnswer() public view override returns (int256) {
    return int256(price_ * 10 ** decimals_);
  }

  function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80) {
    return (0, latestAnswer(), 0, 0, 0);
  }
}
    pragma solidity ^0.8.13;

    import { IMagicLP } from "/mimswap/interfaces/IMagicLP.sol";
    import { ERC20Mock } from "./ERC20Mock.sol";

    contract MagicLPMock is IMagicLP {
      address public _BASE_TOKEN_;
      address public _QUOTE_TOKEN_;
      uint112 public _BASE_RESERVE_;
      uint112 public _QUOTE_RESERVE_;

      constructor(ERC20Mock BASE_TOKEN, ERC20Mock QUOTE_TOKEN) {
        _BASE_TOKEN_ = address(BASE_TOKEN);
        _QUOTE_TOKEN_ = address(QUOTE_TOKEN);
        _BASE_RESERVE_ = uint112(5 * 10 ** ERC20Mock(_BASE_TOKEN_).decimals());
        _QUOTE_RESERVE_ = uint112(5 * 10 ** ERC20Mock(_QUOTE_TOKEN_).decimals());
      }

      function _BASE_TARGET_() external view returns (uint112) {
        return _BASE_RESERVE_;
      }

      function _QUOTE_TARGET_() external view returns (uint112) {
        return _QUOTE_RESERVE_;
      }

      function _I_() external view returns (uint256) {
        return 1 ether;
      }

      function decimals() public view returns (uint8) {
        return ERC20Mock(_BASE_TOKEN_).decimals();
      }

      function getReserves() external view returns (uint256 baseReserve, uint256 quoteReserve) {
        baseReserve = _BASE_RESERVE_;
        quoteReserve = _QUOTE_RESERVE_;
      }

      function getVaultReserve() external view returns (uint256 baseReserve, uint256 quoteReserve) {
        baseReserve = _BASE_RESERVE_;
        quoteReserve = _QUOTE_RESERVE_;
      }

      function totalSupply() external view returns (uint256 totalSupply) {
        totalSupply = 5 * 10 ** decimals();
      }

      function init(
        address baseTokenAddress,
        address quoteTokenAddress,
        uint256 lpFeeRate,
        address mtFeeRateModel,
        uint256 i,
        uint256 k
      ) external {}

      function sellBase(address to) external returns (uint256 receiveQuoteAmount) {}
      function sellQuote(address to) external returns (uint256 receiveBaseAmount) {}
      function flashLoan(uint256 baseAmount, uint256 quoteAmount, address assetTo, bytes calldata data) external {}
      function buyShares(address to) external returns (uint256 shares, uint256 baseInput, uint256 quoteInput) {}
      function sellShares(
        uint256 shareAmount,
        address to,
        uint256 baseMinAmount,
        uint256 quoteMinAmount,
        bytes calldata data,
        uint256 deadline
      ) external returns (uint256 baseAmount, uint256 quoteAmount) {}
      function MIN_LP_FEE_RATE() external view returns (uint256) {}
      function MAX_LP_FEE_RATE() external view returns (uint256) {}
    }

Finally please add below test into MagicLpAggregator.t.sol

import "forge-std/console2.sol";
import { OracleMock } from "./mocks/OracleMock.sol";
import { ERC20Mock } from "./mocks/ERC20Mock.sol";
import { MagicLPMock } from "./mocks/MagicLPMock.sol";

function testOracleDecimals() public {
        IAggregator baseOracle = new OracleMock(8, 4);
        IAggregator quoteOracle = new OracleMock(12, 4);

        ERC20Mock BASE_TOKEN = new ERC20Mock("base", "base");
        ERC20Mock QUOTE_TOKEN = new ERC20Mock("quote", "quote");

        BASE_TOKEN.setDecimals(12);

        MagicLPMock lp = new MagicLPMock(BASE_TOKEN, QUOTE_TOKEN);

        MagicLpAggregatorExt mlAggregator = new MagicLpAggregatorExt(
            lp,
            baseOracle,
            quoteOracle
        );

        uint256 baseOracleAnswerIn18 = uint256(baseOracle.latestAnswer()) * 10 ** (18 - baseOracle.decimals());
        uint256 quoteOracleAnswerIn18 = uint256(quoteOracle.latestAnswer()) * 10 ** (18 - quoteOracle.decimals());
        console2.log('base oracle answer           ==>  ', baseOracle.latestAnswer());
        console2.log('quote roacle answer          ==>  ', quoteOracle.latestAnswer());
        console2.log('base oracle answer in WAD    ==>  ', baseOracleAnswerIn18);
        console2.log('quote oracle answer in WAD   ==>  ', quoteOracleAnswerIn18);

        console2.log("");
        console2.log("**************");
        console2.log("");
        (uint256 baseReserves, uint256 quoteReserves) = lp.getReserves();
        uint256 baseReservesIn18 = baseReserves * 10 ** (18 - BASE_TOKEN.decimals());
        uint256 quoteReservesIn18 = quoteReserves * 10 ** (18 - QUOTE_TOKEN.decimals());
        console2.log('base reserves                ==>  ', baseReserves);
        console2.log('quote reserves               ==>  ', quoteReserves);
        console2.log('base reserves in WAD         ==>  ', baseReservesIn18);
        console2.log('quote reserves in WAD        ==>  ', quoteReservesIn18);

        console2.log("");
        console2.log("**************");
        console2.log("");
        uint8 decimalsOfUsd = 6;
        uint256 totalInUsd = (baseOracleAnswerIn18 * (baseReservesIn18 + quoteReservesIn18) / (10 ** 18) / (10 ** 18)) * 10 ** 6;
        console.log('total usd                     ==>  ', totalInUsd, decimalsOfUsd);

        uint256 totalSupply = lp.totalSupply();
        uint8 decimalsOfLp = lp.decimals();
        console.log('total supply                  ==>  ', totalSupply, decimalsOfLp);

        console2.log("");
        console2.log("**************");
        console2.log("");
        uint256 correctAnswer = (totalInUsd / (10 ** decimalsOfUsd)) / (totalSupply / (10 ** decimalsOfLp)) * 10 ** 18;
        console2.log('correct answer               ==>  ', correctAnswer);
        console2.log('answer of aggregator         ==>  ', uint256(mlAggregator.latestAnswer()));
}

Recommended Mitigation Steps

function latestAnswer() public view override returns (int256) {
        uint256 baseAnswerNomalized = uint256(baseOracle.latestAnswer()) * (10 ** (WAD - baseOracle.decimals()));
        uint256 quoteAnswerNormalized = uint256(quoteOracle.latestAnswer()) * (10 ** (WAD - quoteOracle.decimals()));
        uint256 minAnswer = baseAnswerNomalized < quoteAnswerNormalized ? baseAnswerNomalized : quoteAnswerNormalized;

        (uint256 baseReserve, uint256 quoteReserve) = _getReserves();
        baseReserve = baseReserve * (10 ** (WAD - baseDecimals));
        quoteReserve = quoteReserve * (10 ** (WAD - quoteDecimals));

+        uint256 totalSupply = pair.totalSupply() * (10 ** (WAD - baseDecimals));

-        return int256(minAnswer * (baseReserve + quoteReserve) /
pair.totalSupply());
+        return int256(minAnswer * (baseReserve + quoteReserve) /
totalSupply);
}

0xCalibur (Abracadabra) disputed


The original report as published on Code4rena, by ether_sky. 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 aggregator normalises the reserves and oracle answers to 18 decimals but divides by the raw totalSupply of the MagicLP token without scaling it to 18 decimals, even though the LP token inherits the base token's decimals.

Impact

The aggregator could return a price that is inflated by a factor of 10^(18 - baseDecimals), which may cause a lending protocol using it as a price source to misvalue MagicLP collateral.

What the attacker needed

Base token decimals not 18; MagicLP used as collateral in a Cauldron

The fix

The total supply should be scaled to 18 decimals before being used as the denominator in the price calculation.

How it was found

  1. Deploy mock base and quote tokens with 12 and 18 decimals respectively.
  2. Deploy mock oracles returning prices with 8 and 12 decimals.
  3. Deploy a mock MagicLP with 5 base and 5 quote tokens and a total supply of 5 shares.
  4. Deploy the MagicLpAggregator with these mocks.
  5. Call latestAnswer and compare the result with the correct price computed manually.

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 contract that tells other contracts how much a token is worth. This oracle forgot that the LP token (which represents a share of a pool) can have a different number of decimal places than the standard 18, so it divided by the wrong number and reported a price that was far too high. That could make a lending system think collateral is worth much more than it really is.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by ether_sky

View all

11 more disclosed reports, best first.

More from Abracadabra Mimswap

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.