0

function liquidity() external view returns (uint128)

Which side of the asset pair is referenced here, or is that value in ETH? How do I scale it properly?

1 Answer 1

0

Sorry this answer is so long awaited. I'm trying to catch up the uniswap questons.

So liquidity is the virtual reserves of the √xy

The liquidity when you call a pool contract is the current in range liquidity. Keeping in mind that all liquidity can be stored in multiple active / initiated tick ranges.

For the current tick range you would need to call slot0() and retrieve the current tick, and then call tickSpacing() for the spacing of the pool. Then you would want to divide tick by tick spacing (currentTick / tickSpacing), take the floor of this (drop decimals) and multiply by the tickSpacing. This will give you the lower tick of the active / initiated tick range. Adding the tick spacing to this will give the Upper active / initiated tick range.

You would then use the liquidity from the pool, the current sqrtPriceX96 from slot0 of the pool, the upper and lower ticks of the range, and the decimals of the tokens in the math of this function

async function getTokenAmounts(liquidity,sqrtPriceX96,tickLow,tickHigh,token0Decimal,token1Decimal){
    let sqrtRatioBelow = Math.sqrt(1.0001**tickLow);
    let sqrtRatioAbove = Math.sqrt(1.0001**tickHigh);
    
    let currentTick = getTickAtSqrtRatio(sqrtPriceX96);
    let sqrtPrice = sqrtPriceX96 / Q96;
    
    let amount0wei = 0;
    let amount1wei = 0;
    if(currentTick <= tickLow){
        amount0wei = Math.floor(liquidity*((sqrtRatioAbove-sqrtRatioBelow)/(sqrtRatioBelow*sqrtRatioAbove)));
    }
    else if(currentTick > tickHigh){
        amount1wei = Math.floor(liquidity*(sqrtRatioAbove-sqrtRatioBelow));
    }
    else if(currentTick >= tickLow && currentTick < tickHigh){ 
        amount0wei = Math.floor(liquidity*((sqrtRatioAbove-sqrtPrice)/(sqrtPrice*sqrtRatioAbove)));
        amount1wei = Math.floor(liquidity*(sqrtPrice-sqrtRatioBelow));
    }
    
    let amount0Human = (amount0wei/(10**token0Decimal)).toFixed(token0Decimal);
    let amount1Human = (amount1wei/(10**token1Decimal)).toFixed(token1Decimal);

    console.log("Amount Token0 wei: "+amount0wei);
    console.log("Amount Token1 wei: "+amount1wei);
    console.log("Amount Token0 : "+amount0Human);
    console.log("Amount Token1 : "+amount1Human);
    return [amount0wei, amount1wei]
}

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.