M-07: Large decimal of referenceToken causes overflow at oracle price calculation
Comments
The V3Oracle calculates the Chainlink price using a math formula that can lead to an arithmetic overflow. This is because the formula does not take into account that the reference token decimals will be dynamic and may exceed a value that leads to an overflow. The reference token decimals does not have to be a large value to result in an overflow, in fact even a value of 18 will do. Since the math formula uses basic Solidity math operands and does not rely on standard practices set by Chainlink or other established protocols, the numerator (10 ** referenceTokenDecimals) * chainlinkPriceX96 * Q96 may overflow.
Mitigation
PR #21
To mitigate this, Revert now checks the referenceTokenDecimals and calculates the decimal difference between the reference token and the token. If a difference does exist, the protocol applies the difference to the derived Chainlink price chainlinkPriceX96 * Q96 / chainlinkReferencePriceX96. By applying only the decimal difference to the derived price, we can ensure that an arithmetic overflow does not occur.
If the reference token decimal equals the token decimal, then the Chainlink price is calculated as chainlinkPriceX96 * Q96 / chainlinkReferencePriceX96 and no additional arithmetic is done.
Based on these changes, arithmetic overflow is not possible.
Lines of code
Vulnerability details
C4 issue
M-07: Large decimal of referenceToken causes overflow at oracle price calculation
Comments
The V3Oracle calculates the Chainlink price using a math formula that can lead to an arithmetic overflow. This is because the formula does not take into account that the reference token decimals will be dynamic and may exceed a value that leads to an overflow. The reference token decimals does not have to be a large value to result in an overflow, in fact even a value of 18 will do. Since the math formula uses basic Solidity math operands and does not rely on standard practices set by Chainlink or other established protocols, the numerator
(10 ** referenceTokenDecimals) * chainlinkPriceX96 * Q96
may overflow.Mitigation
PR #21
To mitigate this, Revert now checks the referenceTokenDecimals and calculates the decimal difference between the reference token and the token. If a difference does exist, the protocol applies the difference to the derived Chainlink price
chainlinkPriceX96 * Q96 / chainlinkReferencePriceX96
. By applying only the decimal difference to the derived price, we can ensure that an arithmetic overflow does not occur.If the reference token decimal equals the token decimal, then the Chainlink price is calculated as
chainlinkPriceX96 * Q96 / chainlinkReferencePriceX96
and no additional arithmetic is done.Based on these changes, arithmetic overflow is not possible.
Conclusion
LGTM