sherlock-audit / 2023-05-USSD-judging

9 stars 7 forks source link

sam_gmk - Price returned is always zero #936

Closed sherlock-admin closed 1 year ago

sherlock-admin commented 1 year ago

sam_gmk

high

Price returned is always zero

Summary

Vulnerability Detail

When converting uniswap price from a Q notation ( eg: sqrtPriceX96 ) to actual value ( sqrtPrice ) you divide the sqrtPriceX96 with the 2^k ( k being the number after the X.)

sqrtPrice = sqrtPriceX96 / 2^96

In bitwise operations, >> (SHR), digits are moved, or shifted, to the right Eg: 1010 >> 1 = 101 (in decimal: 10 >> 1 = 5)

Note: M >> n is the same as M / 2^n, therefore:

10 >> 1 = 10 / 2^1 

Steps: Convert from sqrtPriceX96 to sqrtPrice Convert sqrtPrice to Price by multiplying by itself (i.e square) Adjust final price for decimal difference.

So:

sqrtPrice = sqrtPriceX96 / 2^96

or

sqrtPriceX96 >> 96

then

uint256 price = uint256(sqrtPriceX96 >> 96) * uint256(sqrtPriceX96 >> 96)

However, getOwnValuation squares the values first then shifts it with 192. The shift is large such that the value returned will be 0.

 price = uint(sqrtPriceX96)*(uint(sqrtPriceX96))/(1e6) >> (96 * 2);

Impact

price returned is always zero

Code Snippet

https://github.com/sherlock-audit/2023-05-USSD/blob/main/ussd-contracts/contracts/USSDRebalancer.sol#LL74C8-L74C75

Tool used

Manual Review

Recommendation

Follow the official guidelines by uniswap when calculating the exchange rate.

References: https://blog.uniswap.org/uniswap-v3-math-primer#how-do-i-calculate-the-current-exchange-rate

Duplicate of #222