1

This code is from Uniswap v3 development book:

sqrtp_low = price_to_sqrtp(4545)
sqrtp_cur = price_to_sqrtp(5000)
sqrtp_upp = price_to_sqrtp(5500)

def liquidity0(amount, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return (amount * (pa * pb) / q96) / (pb - pa)       # HERE

def liquidity1(amount, pa, pb):
    if pa > pb:
        pa, pb = pb, pa
    return amount * q96 / (pb - pa)          # HERE

eth = 10**18
amount_eth = 1 * eth
amount_usdc = 5000 * eth

liq0 = liquidity0(amount_eth, sqrtp_cur, sqrtp_upp)
liq1 = liquidity1(amount_usdc, sqrtp_cur, sqrtp_low)
liq = int(min(liq0, liq1))

As we already calculated the sqrt of current,lower and upper price why did we divided and multiplied by q96 again?

2 Answers 2

1

q96 is a fixed-point number used for precise calculations I'm not really familiar with Vyper but from my understanding this formula multiplies token amounts and prices, then divides by q96 and price difference (pb - pa)

A fixed-point number is a way of representing decimal numbers in binary format. It is called "fixed" because it has a fixed number of digits to the right of the decimal point. The number of digits to the right of the decimal point is predetermined and does not change, hence the term "fixed".

I suggest you to read this https://blog.finxter.com/data-types-in-solidity-smart-contract-part-20-fixed-point-numbers-address-and-address-type-members/

0

It is the way that fixed point multiplication and division work.

Let's use M = 1000 as the base, so 1 is represented as 1000, 0.5 is represented as 500, etc. Let's suppose we have the numbers: X = x*M, and Y = y*M.

Now X*Y = x*M * y*M = x*y * M*M, we have an extra M so we have to 'scale down' the result X*Y/M = x*y * M.

Similarly for the division X/Y = (x*M)x / (y*M) = x/y and we are missing the M. We have to 'scale up' the result X/Y * M = x/y * M.

For example: X = 1200 and Y = 400, then X*Y / 1000 = 1200*400/1000 = 480. Which is the representation of 1.2 * 0.4 = 0.48.

Similarly X = 1200, Y = 400, then X/Y * 1000 = 1200 / 400 * 1000 = 3000. Which is the representation of 1.2 / 0.4 = 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.