Submitted by obront, also found by cryptostellar5, Tricko, CRYP70, 0xmuxyz, koxuan, 8olidity, yixxas, cozzetti, ktg, and ladboy233
The price() function is expected to return the price of one fractional tokens, represented in base tokens, to 18 decimals of precision. This is laid out clearly in the comments:
/// @notice The current price of one fractional token in base tokens with 18 decimals of precision.
/// @dev Calculated by dividing the base token reserves by the fractional token reserves.
/// @return price The price of one fractional token in base tokens * 1e18.
However, the formula incorrectly calculates the price to be represented in whatever number of decimals the base token is in. Since there are many common base tokens (such as USDC) that will have fewer than 18 decimals, this will create a large mismatch between expected prices and the prices that result from the function.
Prices are calculated with the following formula, where ONE = 1e18:
We know that fractionalTokenReserves will always be represented in 18 decimals. This means that the ONE and the
fractionalTokenReserves will cancel each other out, and we are left with the baseTokenReserves number of decimals for the final price.
As an example:
The formula should use the decimals value of the baseToken to ensure that the decimals of the resulting price ends up with 18 decimals as expected:
This will multiple baseTokenReserves by 1e18, and then additionally by the gap between 1e18 and its own decimals count, which will result in the correct decimals value for the outputted price.
outdoteth (Caviar) confirmed and commented:
