Skip to content
Audit finding Advanced

PriceFeed does not return to the correct price for quote pairs

The PriceFeed contract cannot represent a negative decimal difference between the Pyth and Chainlink oracles, so for certain quote pairs the computed square root price is incorrect. This makes parts of the system unusable for those pairs and could cause further problems if a PriceFeed is added later.

gumgumzum Follow

Originally disclosed on Code4rena

Submitted by gumgumzum

https://github.com/code-423n4/2024-05-predy/blob/main/src/PriceFeed.sol#L29-L59 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/PositionCalculator.sol#L141-L149 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/PositionCalculator.sol#L83 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/PositionCalculator.sol#L70 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/PositionCalculator.sol#L41 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/PositionCalculator.sol#L56 https://github.com/code-423n4/2024-05-predy/blob/main/src/markets/perp/PerpMarketV1.sol#L227 https://github.com/code-423n4/2024-05-predy/blob/main/src/markets/perp/PerpMarketV1.sol#L114-L115 https://github.com/code-423n4/2024-05-predy/blob/main/src/markets/gamma/GammaTradeMarket.sol#L237 https://github.com/code-423n4/2024-05-predy/blob/main/src/markets/gamma/GammaTradeMarket.sol#L286 https://github.com/code-423n4/2024-05-predy/blob/main/src/markets/gamma/GammaTradeMarket.sol#L346 https://github.com/code-423n4/2024-05-predy/blob/main/src/PredyPool.sol#L352-L354 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/logic/TradeLogic.sol#L55-L56 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/logic/TradeLogic.sol#L47-L48 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/logic/ReaderLogic.sol#L35-L36 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/logic/LiquidationLogic.sol#L75-L76 https://github.com/code-423n4/2024-05-predy/blob/main/src/libraries/logic/LiquidationLogic.sol#L141-L142

Impact

Discrepancy in PositionCalculator@getSqrtIndexPrice (cascading down the line to anywhere it is used) when using a PriceFeed or not.

This makes parts of the system unusable for quote pairs (e.g., when selling, position is not safe in PerpMarket since the vault value ends up being very low and the vault margin being negative) and may lead to other problems if at first a PriceFeed is not used but then is updated later since the computed state will change after the update.

Root Cause

contract PriceFeed {
    address private immutable _quotePriceFeed;
    address private immutable _pyth;
    uint256 private immutable _decimalsDiff; // <==== Audit
    bytes32 private immutable _priceId;

    uint256 private constant VALID_TIME_PERIOD = 5 * 60;

    constructor(address quotePrice, address pyth, bytes32 priceId, uint256 decimalsDiff) { // <==== Audit
        _quotePriceFeed = quotePrice;
        _pyth = pyth;
        _priceId = priceId;
        _decimalsDiff = decimalsDiff; // <==== Audit
    }

    /// @notice This function returns the square root of the baseToken price quoted in quoteToken.
    function getSqrtPrice() external view returns (uint256 sqrtPrice) {
        (, int256 quoteAnswer,,,) = AggregatorV3Interface(_quotePriceFeed).latestRoundData();

        IPyth.Price memory basePrice = IPyth(_pyth).getPriceNoOlderThan(_priceId, VALID_TIME_PERIOD);

        require(basePrice.expo == -8, "INVALID_EXP");

        require(quoteAnswer > 0 && basePrice.price > 0);

        uint256 price = uint256(int256(basePrice.price)) * Constants.Q96 / uint256(quoteAnswer);
        price = price * Constants.Q96 / _decimalsDiff; // <==== Audit

        sqrtPrice = FixedPointMathLib.sqrt(price);
    }
}

It’s not possible to create a PriceFeed with a fraction as decimalsDiff. For base pairs, it’s not an issue, but for quote pairs it makes it impossible to get the correct price.

For example, for the USDC/WETH, the base pair PriceFeed would have a 1e12 decimalsDiff but the quote pair PriceFeed should have a 1e12 decimalsDiff which is not possible (the lower you can go is 1e0).

Test

pragma solidity ^0.8.0;

import {Test} from "forge-std/Test.sol";
import {ERC20} from "@solmate/src/tokens/ERC20.sol";
import {IUniswapV3Factory} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";

import {AddPairLogic, PredyPool, Perp, IPredyPool} from "../../src/PredyPool.sol";
import {PriceFeed} from "../../src/PriceFeed.sol";
import {InterestRateModel} from "../../src/libraries/InterestRateModel.sol";

contract PriceFeedDiscrepancyTest is Test {
    PredyPool predyPool;

    uint128 internal constant RISK_RATIO = 109544511;
    uint128 internal constant BASE_MIN_COLLATERAL_WITH_DEBT = 2000;

    address admin = vm.addr(100);

    ERC20 USDC = ERC20(0xaf88d065e77c8cC2239327C5EDb3A432268e5831);
    ERC20 WETH = ERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1);

    bytes32 USDC_PYTH_PRICE_ID =
        0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a;
    bytes32 WETH_PYTH_PRICE_ID =
        0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace;

    address USDC_CHAINLINK_PRICE_FEED =
        0x50834F3163758fcC1Df9973b6e91f0F0F0434aD3;
    address WETH_CHAINLINK_PRICE_FEED =
        0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612;

    IUniswapV3Factory uniswapFactory =
        IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);

    address pyth = 0xff1a0f4744e8582DF1aE09D5611b887B6a12925C;

    function setUp() public {
        vm.label(admin, "ADMIN");
        vm.label(address(USDC), "USDC");
        vm.label(address(WETH), "WETH");

        vm.createSelectFork(vm.envString("ALCHEMY_RPC_URL"));

        vm.startPrank(admin);
        predyPool = new PredyPool();
        predyPool.initialize(address(uniswapFactory));
    }

    function testSqrtIndexPrice() public {
        vm.startPrank(admin);
        PriceFeed quotePriceFeed = new PriceFeed(
            WETH_CHAINLINK_PRICE_FEED,
            pyth,
            USDC_PYTH_PRICE_ID,
            1e0
        );

        PriceFeed basePriceFeed = new PriceFeed(
            USDC_CHAINLINK_PRICE_FEED,
            pyth,
            WETH_PYTH_PRICE_ID,
            1e12
        );

        address pool = uniswapFactory.getPool(
            address(USDC),
            address(WETH),
            500
        );

        uint256 quotePair = registerPair(pool, address(WETH), address(0), true);
        uint256 basePair = registerPair(pool, address(USDC), address(0), true);

        uint256 quoteIndexPriceBefore = predyPool.getSqrtIndexPrice(quotePair);
        uint256 baseIndexPriceBefore = predyPool.getSqrtIndexPrice(basePair);

        predyPool.updatePriceOracle(quotePair, address(quotePriceFeed));
        predyPool.updatePriceOracle(basePair, address(basePriceFeed));

        assertApproxEqRel(
            baseIndexPriceBefore,
            predyPool.getSqrtIndexPrice(basePair),
            1e16
        );
        assertApproxEqRel(
            quoteIndexPriceBefore,
            predyPool.getSqrtIndexPrice(quotePair),
            1e16
        );
    }

    function registerPair(
        address pool,
        address quoteToken,
        address priceFeed,
        bool isWhitelistEnabled
    ) internal returns (uint256) {
        InterestRateModel.IRMParams memory irmParams = InterestRateModel
            .IRMParams(1e16, 9 * 1e17, 5 * 1e17, 1e18);

        return
            predyPool.registerPair(
                AddPairLogic.AddPairParams(
                    quoteToken,
                    admin,
                    pool,
                    priceFeed,
                    isWhitelistEnabled,
                    0,
                    Perp.AssetRiskParams(
                        RISK_RATIO,
                        BASE_MIN_COLLATERAL_WITH_DEBT,
                        1000,
                        500,
                        1005000,
                        1050000
                    ),
                    irmParams,
                    irmParams
                )
            );
    }
}

Results

❯ forge test --match-contract PriceFeedDiscrepancyTest -vv
[⠢] Compiling...
No files changed, compilation skipped

Ran 1 test for test/fork/PriceFeedDiscrepancy.t.sol:PriceFeedDiscrepancyTest
[FAIL. Reason: assertion failed] testSqrtIndexPrice() (gas: 4948278)
Logs:
  Error: a ~= b not satisfied [uint]
          Left: 1333136901050186247877690170972068
         Right: 1331884368549106242288122906
   Max % Delta: 1.000000000000000000
       % Delta: 100093942.135387808257073200

Suite result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 17.83ms (4.19ms CPU time)

Ran 1 test suite in 342.31ms (17.83ms CPU time): 0 tests passed, 1 failed, 0 skipped (1 total tests)

Failing tests:
Encountered 1 failing test in test/fork/PriceFeedDiscrepancy.t.sol:PriceFeedDiscrepancyTest
[FAIL. Reason: assertion failed] testSqrtIndexPrice() (gas: 4948278)

Encountered a total of 1 failing tests, 0 tests succeeded

Recommended Mitigation Steps

diff --git a/src/PriceFeed.sol b/src/PriceFeed.sol
index a8cd985..bd0152d 100644
--- a/src/PriceFeed.sol
+++ b/src/PriceFeed.sol
@@ -9,13 +9,13 @@ import {Constants} from "./libraries/Constants.sol";
 contract PriceFeedFactory {
     address private immutable _pyth;

-    event PriceFeedCreated(address quotePrice, bytes32 priceId, uint256 decimalsDiff, address priceFeed);
+    event PriceFeedCreated(address quotePrice, bytes32 priceId, int256 decimalsDiff, address priceFeed);

     constructor(address pyth) {
         _pyth = pyth;
     }

-    function createPriceFeed(address quotePrice, bytes32 priceId, uint256 decimalsDiff) external returns (address) {
+    function createPriceFeed(address quotePrice, bytes32 priceId, int256 decimalsDiff) external returns (address) {
         PriceFeed priceFeed = new PriceFeed(quotePrice, _pyth, priceId, decimalsDiff);

         emit PriceFeedCreated(quotePrice, priceId, decimalsDiff, address(priceFeed));
@@ -29,12 +29,12 @@ contract PriceFeedFactory {
 contract PriceFeed {
     address private immutable _quotePriceFeed;
     address private immutable _pyth;
-    uint256 private immutable _decimalsDiff;
+    int256 private immutable _decimalsDiff;
     bytes32 private immutable _priceId;

     uint256 private constant VALID_TIME_PERIOD = 5 * 60;

-    constructor(address quotePrice, address pyth, bytes32 priceId, uint256 decimalsDiff) {
+    constructor(address quotePrice, address pyth, bytes32 priceId, int256 decimalsDiff) {
         _quotePriceFeed = quotePrice;
         _pyth = pyth;
         _priceId = priceId;
@@ -52,7 +52,12 @@ contract PriceFeed {
         require(quoteAnswer > 0 && basePrice.price > 0);

         uint256 price = uint256(int256(basePrice.price)) * Constants.Q96 / uint256(quoteAnswer);
-        price = price * Constants.Q96 / _decimalsDiff;
+
+        if (_decimalsDiff > 0) {
+            price = price * Constants.Q96 / 10 ** uint256(_decimalsDiff);
+        } else {
+            price = price * Constants.Q96 * 10 ** uint256(-_decimalsDiff);
+        }

         sqrtPrice = FixedPointMathLib.sqrt(price);
     }

Assessed type

Oracle

syuhei176 (Predy) disputed and commented:

I don’t understand the issue you’re pointing out. The PriceFeed represents the square root of the price of the baseToken in terms of the quoteToken, and it’s not necessary to have separate prices for both the baseToken and the quoteToken.

As for the recommended mitigation steps, it’s using (-_decimalsDiff) in the condition where _decimalsDiff is negative, and it seems doing the same thing for both conditions.

0xsomeone (judge) commented:

The Warden states that the price normalization step in the PriceFeed contract does not account for a “negative” decimal difference (i.e., requiring a multiplication instead of a division).

I do not believe the described vulnerability holds true as the oracle can always be created in the “positive” decimal direction, and the square root encoded price can be decoded and utilized in the inverse direction. As such, a PriceFeed configured for the WETH/USDC direction can be used in the USDC/WETH direction without necessitating a different PriceFeed deployment.

gumgumzum (warden) commented:

@0xsomeone - That is unfortunately incorrect due to how PositionCalculator@getSqrtIndexPrice works:

    function getSqrtIndexPrice(DataType.PairStatus memory pairStatus) internal view returns (uint256 sqrtPriceX96) {
        if (pairStatus.priceFeed != address(0)) {
            return PriceFeed(pairStatus.priceFeed).getSqrtPrice();
        } else {
            return UniHelper.convertSqrtPrice(
                UniHelper.getSqrtTWAP(pairStatus.sqrtAssetStatus.uniswapPool), pairStatus.isQuoteZero
            );
        }
    }

When using a PriceFeed, it directly returns the price returned from the PriceFeed regardless of whether the pair is a base or a quote pair. Otherwise, it uses the Uniswap Sqrt TWAP and converts it based on whether the pair is a base pair or a quote pair.

So it’s not possible to use the same PriceFeed for both a base and quote pair otherwise PositionCalculator@getSqrtIndexPrice would return the same price for both pairs which is wrong.

Here is a modified POC that demonstrates that:

pragma solidity ^0.8.0;

import {Test} from "forge-std/Test.sol";
import {ERC20} from "@solmate/src/tokens/ERC20.sol";
import {IUniswapV3Factory} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";

import {AddPairLogic, PredyPool, Perp, IPredyPool} from "../../src/PredyPool.sol";
import {PriceFeed} from "../../src/PriceFeed.sol";
import {InterestRateModel} from "../../src/libraries/InterestRateModel.sol";

contract PriceFeedDiscrepancyTest is Test {
    PredyPool predyPool;

    uint128 internal constant RISK_RATIO = 109544511;
    uint128 internal constant BASE_MIN_COLLATERAL_WITH_DEBT = 2000;

    address admin = vm.addr(100);

    ERC20 USDC = ERC20(0xaf88d065e77c8cC2239327C5EDb3A432268e5831);
    ERC20 WETH = ERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1);

    bytes32 USDC_PYTH_PRICE_ID =
        0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a;
    bytes32 WETH_PYTH_PRICE_ID =
        0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace;

    address USDC_CHAINLINK_PRICE_FEED =
        0x50834F3163758fcC1Df9973b6e91f0F0F0434aD3;
    address WETH_CHAINLINK_PRICE_FEED =
        0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612;

    IUniswapV3Factory uniswapFactory =
        IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);

    address pyth = 0xff1a0f4744e8582DF1aE09D5611b887B6a12925C;

    function setUp() public {
        vm.label(admin, "ADMIN");
        vm.label(address(USDC), "USDC");
        vm.label(address(WETH), "WETH");

        vm.createSelectFork(vm.envString("ALCHEMY_RPC_URL"));

        vm.startPrank(admin);
        predyPool = new PredyPool();
        predyPool.initialize(address(uniswapFactory));
    }

    function testSqrtIndexPrice() public {
        vm.startPrank(admin);

        PriceFeed basePriceFeed = new PriceFeed(
            USDC_CHAINLINK_PRICE_FEED,
            pyth,
            WETH_PYTH_PRICE_ID,
            1e12
        );

        address pool = uniswapFactory.getPool(
            address(USDC),
            address(WETH),
            500
        );

        uint256 quotePair = registerPair(pool, address(WETH), address(0), true);
        uint256 basePair = registerPair(pool, address(USDC), address(0), true);

        uint256 quoteIndexPriceBefore = predyPool.getSqrtIndexPrice(quotePair);
        uint256 baseIndexPriceBefore = predyPool.getSqrtIndexPrice(basePair);

        predyPool.updatePriceOracle(quotePair, address(basePriceFeed)); // <===== Modified this
        predyPool.updatePriceOracle(basePair, address(basePriceFeed));

        assertApproxEqRel(
            baseIndexPriceBefore,
            predyPool.getSqrtIndexPrice(basePair),
            1e16
        );
        assertApproxEqRel(
            quoteIndexPriceBefore,
            predyPool.getSqrtIndexPrice(quotePair),
            1e16
        );
    }

    function registerPair(
        address pool,
        address quoteToken,
        address priceFeed,
        bool isWhitelistEnabled
    ) internal returns (uint256) {
        InterestRateModel.IRMParams memory irmParams = InterestRateModel
            .IRMParams(1e16, 9 * 1e17, 5 * 1e17, 1e18);

        return
            predyPool.registerPair(
                AddPairLogic.AddPairParams(
                    quoteToken,
                    admin,
                    pool,
                    priceFeed,
                    isWhitelistEnabled,
                    0,
                    Perp.AssetRiskParams(
                        RISK_RATIO,
                        BASE_MIN_COLLATERAL_WITH_DEBT,
                        1000,
                        500,
                        1005000,
                        1050000
                    ),
                    irmParams,
                    irmParams
                )
            );
    }
}

Its results:

❯ forge test --match-contract PriceFeedDiscrepancyTest -vv
[⠢] Compiling...
No files changed, compilation skipped

Ran 1 test for test/fork/PriceFeedDiscrepancy.t.sol:PriceFeedDiscrepancyTest
[FAIL. Reason: assertion failed] testSqrtIndexPrice() (gas: 4934707)
Logs:
  Error: a ~= b not satisfied [uint]
          Left: 1361087074510534603633354914613524
         Right: 4611728606150998419235085
   Max % Delta: 1.000000000000000000
       % Delta: 29513598612.100135584576446400

Suite result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 15.36s (13.24s CPU time)

Ran 1 test suite in 15.38s (15.36s CPU time): 0 tests passed, 1 failed, 0 skipped (1 total tests)

Failing tests:
Encountered 1 failing test in test/fork/PriceFeedDiscrepancy.t.sol:PriceFeedDiscrepancyTest
[FAIL. Reason: assertion failed] testSqrtIndexPrice() (gas: 4934707)

Encountered a total of 1 failing tests, 0 tests succeeded

0xsomeone (judge) commented:

@gumgumzum, a sqrtPriceX96 data point can be decoded in two directions, and you can see an example of that here. The PoC provided does not adequately utilize the price measurement.

gumgumzum (warden) commented:

@0xsomeone - the PoC provided clearly shows that the price returned from PredyPool@getSqrtIndexPrice is wrong when using a PriceFeed. This functions calls PositionCalculator@getSqrtIndexPrice directly, which is not converting the price when using a PriceFeed.

The result PredyPool@getSqrtIndexPrice is used directly without conversion throughout the protocol, for example: here and here.

0xsomeone (judge) commented:

EDIT 2: As a disclaimer, some contents of this reply are misconceived/incorrect and it should not be regarded as correct.

@gumgumzum, I do not see any problem with the instances utilized as they both treat the reported price as a square root price. The system will configure a particular pair in one direction (the direction with a positive decimal difference), and that is acceptable.

I will notify the Sponsor to have a second look at this submission but will retain my original invalidation ruling for now. If any further feedback is needed, it will be explicitly requested.

EDIT: After thoroughly revisiting, it appears the _decimalDiff was meant to accommodate for decimal differences in the oracles, not the tokens. The main problem here is that it can only be used as a divisor and the multiplicand of the overall price calculation is the Pyth oracle, meaning that if the Pyth oracle has fewer decimals than the Chainlink oracle a proper PriceFeed will not be configurable.

syuhei176 (Predy) commented:

@gumgumzum - now I understand the issue presented in this report.

For example, when registering the BTC/DAI pair,

  • BTC has decimals = 8 and
  • DAI has decimals = 18,
  • So decimalsDiff should be -10**10.

However, the PriceFeed does not allow the registration of negative decimals. I believe this report is valid.

0xsomeone (judge) commented:

EDIT: As a disclaimer, some contents of this reply are misconceived/incorrect and it should not be regarded as correct.

@syuhei176 - I would like to make sure everyone is aligned in relation to this submission.

The problem with the current PriceFeed is not related to the decimals of the underlying tokens. It is related to the decimals of the oracle measurements.

A square root encoded Uniswap V3 price is expected to be in the following form:

Note: please see scenario in judge’s original comment.

The final operation of the code in the PriceFeed is:

sqrtPrice = FixedPointMathLib.sqrt(price);

We can raise both equations to the power of 2 to understand what price is meant to represent:

Note: please see scenario in judge’s original comment.

The actual calculations of price should always yield the price of the asset extrapolated by 2^{96} twice, and we have the following code to deduce this:

uint256 price = uint256(int256(basePrice.price)) * Constants.Q96 / uint256(quoteAnswer);
price = price * Constants.Q96 / _decimalsDiff;

As we can observe above, the code will deduce the price of the asset by dividing the Pyth Network price by the Chainlink price and multiplying that by 2^{96} (Constants.Q96) twice on each multiplication and division operation to preserve accuracy.

In the above code segment, the _decimalsDiff variable is solely needed when the price measurements of the assets are reported in different decimal denominations. The _decimalsDiff variable presently supports only a positive decimal difference between the Pyth Network oracle and the Chainlink oracle (i.e., the Pyth Network oracle should always have a higher or equal accuracy when compared to the Chainlink oracle).

Based on the audit’s scope, the assets that are meant to be supported are:

Question | Answer |

ERC20 used by the protocol | WETH, USDC, ARB, USDT, DAI, WBTC |

All these assets share USD based oracle measurements (as the oracles need to have a common base), and all oracles support 8 decimals of accuracy. As such, the current code will work as expected with the current list of supported assets by configuring the _decimalsDiff to be 1 (i.e., a no-op).

While I fully understand the concerns the Warden raises, I do not believe the code presently manifests itself as a vulnerability based on the audit’s description. In reality, all EIP-20 assets can be utilized safely as long as their Chainlink and Pyth Network oracles have 8 decimals which is true for all USD-denominated oracles.

What I do see is incorrect code, as the _decimalsDiff concept should not exist in the PriceFeed in the first place based on how the PriceFeed is meant to operate. We can incorporate the recommendations of the Warden into the codebase to ensure that the PriceFeed supports an arbitrary decimal difference between the oracle measurements, however, such a feature would not be used with the current configuration of the system and would never be utilized when using USD-based oracle measurements.

I invite the Warden to refute any of the points I have raised, and the Sponsor to re-evaluate the submission’s validity in light of the above.

syuhei176 (Predy) commented:

The final output of the PriceFeed, sqrtPriceX96, follows the same concept as used in Uniswap. For example, in the case of BTC/DAI, if 1 BTC is $60,000, it would be calculated as follows:

sqrtPriceX96 = (1 * 10**8) * (2**96) / 60000 * 10**18

Therefore, this also involves the issue of the underlying token’s decimals.

0xsomeone (judge) commented:

The sqrtPriceX96 can be decoded to an arbitrary precision as it represents a ratio between the tokens with 96 fixed point precision.

In the case of BTC/DAI, the present code would calculate that for every BTC we need 60.000 DAI. The question of decimals is reliant on the code that integrates with the square root encoded price.

You can confirm this by the Uniswap V3/V4 documentation as well as this Stack Overflow thread here which demonstrates that the live deployment of Uniswap V3 is also decimal agnostic.

EDIT: As a clarification, this reply is somewhat misleading as the sqrtPriceX96 does not directly have a concept of decimals but will yield a price ratio between two assets that factors in decimals.

syuhei176 (Predy) commented:

I made a mistake. I meant to say:

sqrtPriceX96 = (60000 * 10**18) * (2**96) / (1 * 10**8)

0xsomeone (judge) commented:

I have revisited the issue with the assistance of @syuhei176 and have concluded that the submission is indeed incorrect. While the sqrtPriceX96 measurement does not follow a concept of “decimals”, it still accommodates them by offsetting the relevant exchange rate. So in case a 1:1 exchange rate between WBTC (8 decimals) and ETH (18 decimals) was meant to be depicted via a sqrtPriceX96, the value would be as follows:

Note: please see scenario in judge’s original comment.

As the code does not support a negative decimal offset, it will be impossible to depict certain pair configurations correctly via the PriceFeed. I believe a medium risk rating is better suited for this submission as it would infer that certain tokens will not be supported rather than there being an active loss or vulnerability in the system. I have re-instated its state as a satisfactory finding and was unable to find a duplicate within this repository or the validation one that would merit a reward.

**[syuhei176 (Pr

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

The `_decimalsDiff` parameter is an unsigned integer and is always used as a divisor, so it cannot represent a negative difference that would require multiplication.

Impact

Parts of the system become unusable for quote pairs (e.g., selling may show the position as unsafe because the vault value is very low and margin negative), and later adding a PriceFeed can change the computed state.

What the attacker needed

A quote pair with a negative decimal difference; a PriceFeed is used for that pair

The fix

The fix should allow a signed decimal difference and apply multiplication when the difference is negative, as shown in the recommended mitigation.

How it was found

  1. Deploy a PriceFeed for the quote pair with a decimalsDiff of 1e0.
  2. Deploy a PriceFeed for the base pair with a decimalsDiff of 1e12.
  3. Register both pairs and record their initial square root index prices.
  4. Update the price oracles for both pairs to use the deployed PriceFeeds.
  5. Compare the new square root index prices with the initial ones; the quote pair's price is far off.

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 feed is a service that gives the current price of an asset. This report says that when two price sources use different numbers of decimal places, the code that combines them can only handle one direction of the difference. For some trading pairs this makes the calculated price wrong, which can break trading or cause losses.

More from Predy

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.