Skip to content
Audit finding Advanced

Token amounts are scaled up twice causing the amounts to be inflated in two token vault

Token amounts were scaled to 18 decimals twice before being passed to Balancer's stable math functions, inflating balances for tokens with fewer than 18 decimals. This caused the spot price check to fail and revert, breaking the vault's reinvest function and preventing strategy tokens from appreciating.

xiaoming90 Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2022-12-notional-judging/issues/13

Found by

xiaoming90

Summary

Token amounts are scaled up twice causing the amounts to be inflated in two token vault when performing computation. This in turn causes the reinvest function to break leading to a loss of assets for vault users, and the value of their strategy tokens will be struck and will not appreciate.

Vulnerability Detail

In Line 121-124, the primaryAmount and secondaryAmount are scaled up to BALANCER_PRECISION (1e18). The reason for doing so is that balancer math functions expect all amounts to be in BALANCER_PRECISION (1e18).

Then, the scaled primaryAmount and secondaryAmount are passed into the _getSpotPrice function at Line 126.

https://github.com/sherlock-audit/2022-12-notional/blob/main/contracts/vaults/balancer/internal/math/Stable2TokenOracleMath.sol#L99

Solidity
File: Stable2TokenOracleMath.sol
099:     function _validateSpotPriceAndPairPrice(
100:         StableOracleContext calldata oracleContext,
101:         TwoTokenPoolContext calldata poolContext,
102:         StrategyContext memory strategyContext,
103:         uint256 oraclePrice,
104:         uint256 primaryAmount, 
105:         uint256 secondaryAmount
106:     ) internal view {
107:         // Oracle price is always specified in terms of primary, so tokenIndex == 0 for primary
108:         uint256 spotPrice = _getSpotPrice({
109:             oracleContext: oracleContext,
110:             poolContext: poolContext,
111:             primaryBalance: poolContext.primaryBalance,
112:             secondaryBalance: poolContext.secondaryBalance,
113:             tokenIndex: 0
114:         });
115: 
116:         /// @notice Check spotPrice against oracle price to make sure that 
117:         /// the pool is not being manipulated
118:         _checkPriceLimit(strategyContext, oraclePrice, spotPrice);
119: 
120:         /// @notice Balancer math functions expect all amounts to be in BALANCER_PRECISION
121:         uint256 primaryPrecision = 10 ** poolContext.primaryDecimals;
122:         uint256 secondaryPrecision = 10 ** poolContext.secondaryDecimals;
123:         primaryAmount = primaryAmount * BalancerConstants.BALANCER_PRECISION / primaryPrecision;
124:         secondaryAmount = secondaryAmount * BalancerConstants.BALANCER_PRECISION / secondaryPrecision;
125: 
126:         uint256 calculatedPairPrice = _getSpotPrice({
127:             oracleContext: oracleContext,
128:             poolContext: poolContext,
129:             primaryBalance: primaryAmount,
130:             secondaryBalance: secondaryAmount,
131:             tokenIndex: 0
132:         });

Within the _getSpotPrice function, the primaryBalance and secondaryBalance are scaled up again at Line 25 - 28. As such, any token (e.g. USDC) with a decimal of less than BALANCER_PRECISION (1e18) will be scaled up twice. This will cause the balanceX or balanceY to be inflated.

https://github.com/sherlock-audit/2022-12-notional/blob/main/contracts/vaults/balancer/internal/math/Stable2TokenOracleMath.sol#L15

Solidity
File: Stable2TokenOracleMath.sol
15:     function _getSpotPrice(
16:         StableOracleContext memory oracleContext, 
17:         TwoTokenPoolContext memory poolContext, 
18:         uint256 primaryBalance,
19:         uint256 secondaryBalance,
20:         uint256 tokenIndex
21:     ) internal view returns (uint256 spotPrice) {
22:         require(tokenIndex < 2); /// @dev invalid token index
23: 
24:         /// Apply scale factors
25:         uint256 scaledPrimaryBalance = primaryBalance * poolContext.primaryScaleFactor 
26:             / BalancerConstants.BALANCER_PRECISION;
27:         uint256 scaledSecondaryBalance = secondaryBalance * poolContext.secondaryScaleFactor 
28:             / BalancerConstants.BALANCER_PRECISION;
29: 
30:         /// @notice poolContext balances are always in BALANCER_PRECISION (1e18)
31:         (uint256 balanceX, uint256 balanceY) = tokenIndex == 0 ?
32:             (scaledPrimaryBalance, scaledSecondaryBalance) :
33:             (scaledSecondaryBalance, scaledPrimaryBalance);
34: 
35:         uint256 invariant = StableMath._calculateInvariant(
36:             oracleContext.ampParam, StableMath._balances(balanceX, balanceY), true // round up
37:         );
38: 
39:         spotPrice = StableMath._calcSpotPrice({
40:             amplificationParameter: oracleContext.ampParam,
41:             invariant: invariant,
42:             balanceX: balanceX,
43:             balanceY: balanceY
44:         });
45: 
46:         /// Apply secondary scale factor in reverse
47:         uint256 scaleFactor = tokenIndex == 0 ?
48:             poolContext.secondaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.primaryScaleFactor :
49:             poolContext.primaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.secondaryScaleFactor;
50:         spotPrice = spotPrice * BalancerConstants.BALANCER_PRECISION / scaleFactor;
51:     }

Balancer's Scaling Factors

It is important to know the underlying mechanism of scaling factors within Balancer to understand this issue.

Within Balancer, all stable math calculations within the Balancer's pools are performed in 1e18. Thus, before passing the token balances to the stable math functions, all the balances need to be normalized to 18 decimals.

For instance, assume that 100 USDC needs to be passed into the stable math functions for some computation. 100 USDC is equal to 100e6 since the decimals of USDC is 6. To normalize it to 18 decimals, 100 USDC (100e6) will be multiplied by its scaling factor (1e12), and the result will be 100e18.

The following code taken from Balancer shows that the scaling factor is comprised of the scaling factor multiplied by the token rate. The scaling factor is the value needed to normalize the token balance to 18 decimals.

https://etherscan.io/address/0x32296969Ef14EB0c6d29669C550D4a0449130230#code

Solidity
    /**
     * @dev Overrides scaling factor getter to introduce the tokens' price rate.
     * Note that it may update the price rate cache if necessary.
     */
    function _scalingFactors() internal view virtual override returns (uint256[] memory scalingFactors) {
        // There is no need to check the arrays length since both are based on `_getTotalTokens`
        // Given there is no generic direction for this rounding, it simply follows the same strategy as the BasePool.
        scalingFactors = super._scalingFactors();
        scalingFactors[0] = scalingFactors[0].mulDown(_priceRate(_token0));
        scalingFactors[1] = scalingFactors[1].mulDown(_priceRate(_token1));
    }

Another point to note is that Balancer's stable math functions perform calculations in fixed point format. Therefore, the scaling factor will consist of the FixedPoint.ONE (1e18) multiplied by the value needed to normalize the token balance to 18 decimals. If it is a USDC with 6 decimals, the scaling factor will be 1e30:

Solidity
FixedPoint.ONE * 10**decimalsDifference
1e18 * 1e12 = 1e30

https://etherscan.io/address/0x32296969Ef14EB0c6d29669C550D4a0449130230#code

Solidity
    /**
     * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
     * it had 18 decimals.
     */
    function _computeScalingFactor(IERC20 token) internal view returns (uint256) {
        // Tokens that don't implement the `decimals` method are not supported.
        uint256 tokenDecimals = ERC20(address(token)).decimals();

        // Tokens with more than 18 decimals are not supported.
        uint256 decimalsDifference = Math.sub(18, tokenDecimals);
        return FixedPoint.ONE * 10**decimalsDifference;
    }

Proof-of-Concept

Assume that one of the tokens in Notional's two token leverage vault has a decimal of less than 18. Let's take USDC as an example.

  1. 100 USDC (1e6) is passed into the _validateSpotPriceAndPairPrice function as the primaryAmount. In Line 121-124 of the _validateSpotPriceAndPairPrice function, the primaryAmount will be scaled up to BALANCER_PRECISION (1e18).

    Solidity
    primaryAmount = primaryAmount * BalancerConstants.BALANCER_PRECISION / primaryPrecision;
    primaryAmount = 100e6 * 1e18 / 1e6
    primaryAmount = 100e18
    
  2. Within the _getSpotPrice function, the primaryBalance is scaled up again at Line 25 - 28 of the _getSpotPrice function.

    Solidity
    scaledPrimaryBalance = primaryBalance * poolContext.primaryScaleFactor / BalancerConstants.BALANCER_PRECISION;
    scaledPrimaryBalance = 100e18 * 1e30 / 1e18
    scaledPrimaryBalance = 1e30
    scaledPrimaryBalance = 1000000000000e18
    

    As shown above, normalized 100 USDC (100e18) ended up becoming normalized 1000000000000 USDC (1000000000000e18). Therefore, the stable math functions are computed with an inflated balance of 1000000000000 USDC instead of 100 USDC.

Impact

The spot price computed by the Stable2TokenOracleMath._getSpotPrice function will deviate from the actual price because inflated balances were passed into it. The deviated spot price will then be passed to the _checkPriceLimit function to verify if the spot price has deviated from the oracle price. The check will fail and cause a revert. This will in turn cause the Stable2TokenOracleMath._validateSpotPriceAndPairPrice function to revert.

Therefore, any function that relies on the Stable2TokenOracleMath._validateSpotPriceAndPairPrice function will be affected. It was found that the MetaStable2TokenAuraHelper.reinvestReward relies on the Stable2TokenOracleMath._validateSpotPriceAndPairPrice function. As such, reinvest feature of the vault will be broken and the vault will not be able to reinvest its rewards.

This in turn led to a loss of assets for vault users, and the value of their strategy tokens will be struck and will not appreciate.

Code Snippet

https://github.com/sherlock-audit/2022-12-notional/blob/main/contracts/vaults/balancer/internal/math/Stable2TokenOracleMath.sol#L99

https://github.com/sherlock-audit/2022-12-notional/blob/main/contracts/vaults/balancer/internal/math/Stable2TokenOracleMath.sol#L15

Tool used

Manual Review

Recommendation

Since the token balances are already normalized to 18 decimals within the _getSpotPrice function, the code to normalize the token balances in the _validateSpotPriceAndPairPrice function can be removed.

Diff
    function _validateSpotPriceAndPairPrice(
        StableOracleContext calldata oracleContext,
        TwoTokenPoolContext calldata poolContext,
        StrategyContext memory strategyContext,
        uint256 oraclePrice,
        uint256 primaryAmount, 
        uint256 secondaryAmount
    ) internal view {
        // Oracle price is always specified in terms of primary, so tokenIndex == 0 for primary
        uint256 spotPrice = _getSpotPrice({
            oracleContext: oracleContext,
            poolContext: poolContext,
            primaryBalance: poolContext.primaryBalance,
            secondaryBalance: poolContext.secondaryBalance,
            tokenIndex: 0
        });

        /// @notice Check spotPrice against oracle price to make sure that 
        /// the pool is not being manipulated
        _checkPriceLimit(strategyContext, oraclePrice, spotPrice);

-        /// @notice Balancer math functions expect all amounts to be in BALANCER_PRECISION
-        uint256 primaryPrecision = 10 ** poolContext.primaryDecimals;
-        uint256 secondaryPrecision = 10 ** poolContext.secondaryDecimals;
-        primaryAmount = primaryAmount * BalancerConstants.BALANCER_PRECISION / primaryPrecision;
-        secondaryAmount = secondaryAmount * BalancerConstants.BALANCER_PRECISION / secondaryPrecision;

        uint256 calculatedPairPrice = _getSpotPrice({
            oracleContext: oracleContext,
            poolContext: poolContext,
            primaryBalance: primaryAmount,
            secondaryBalance: secondaryAmount,
            tokenIndex: 0
        });

        /// @notice Check the calculated primary/secondary price against the oracle price
        /// to make sure that we are joining the pool proportionally
        _checkPriceLimit(strategyContext, oraclePrice, calculatedPairPrice);
    }

Discussion

weitianjie2000

valid, will fix

The original report as published on Sherlock, by xiaoming90. 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

The code normalised token amounts to 18 decimals in _validateSpotPriceAndPairPrice and then normalised them again inside _getSpotPrice, double-scaling balances for tokens with fewer than 18 decimals.

Impact

The reinvest feature of the vault is broken, which could lead to a loss of assets for vault users and prevent the value of their strategy tokens from appreciating.

What the attacker needed

A vault token with fewer than 18 decimals

The fix

The normalisation in _validateSpotPriceAndPairPrice should be removed because _getSpotPrice already normalises the balances.

How it was found

  1. Pass an amount of a token with fewer than 18 decimals, such as USDC, into _validateSpotPriceAndPairPrice.
  2. The function scales the amount up to 18 decimals.
  3. The scaled amount is passed to _getSpotPrice, which scales it up again.
  4. The inflated balance produces a spot price that deviates from the oracle price.
  5. The price limit check fails and the function reverts, breaking reinvestReward.

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.

Some tokens like USDC have 6 decimal places instead of the usual 18. The code tried to convert amounts to 18 decimals, but did it twice, making the numbers a trillion times too big. That made a price safety check fail, so the vault could not reinvest its rewards.

More by xiaoming90

View all

122 more disclosed reports, best first.

More from Notional Update #4

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.