In Uniswap V3, getting different prices of 1 WETH to USDC while swapping and adding liquidity, potentially because of fees and other contributing factors.
Swap
Add Liquidity
Programmatically, I'm calculating the amounts using this JS code:
const JSBI = require('jsbi') const { ethers } = require("ethers"); const { TickMath, FullMath } = require('@uniswap/v3-sdk') const UniswapV3FactoryABI = require('./abis/UniswapV3Factory.json'); const UniswapV3PoolABI = require('./abis/UniswapV3Pool.json'); const RPC_URL = "JSON_RPC_URL" const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; // quote const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; // base const provider = new ethers.JsonRpcProvider(RPC_URL); const uniswapV3Factory = "0x1F98431c8aD98523631AE4a59f267346ea31F984"; const factoryContract = new ethers.Contract( uniswapV3Factory, UniswapV3FactoryABI, provider ); async function getCurrentTick(fee) { const poolAddress = await factoryContract.getPool(WETH, USDC, fee); const poolContract = new ethers.Contract( poolAddress, UniswapV3PoolABI, provider ); console.log(poolAddress); const slot0 = await poolContract.slot0(); const currentTick = parseInt(slot0.tick); return currentTick; } async function main( inputAmount, baseTokenDecimals, quoteTokenDecimals, fee ) { const currentTick = await getCurrentTick(fee); // console.log(currentTick) const sqrtRatioX96 = TickMath.getSqrtRatioAtTick(currentTick); const ratioX192 = JSBI.multiply(sqrtRatioX96, sqrtRatioX96); const baseAmount = JSBI.BigInt(inputAmount * (10 ** baseTokenDecimals)); const shift = JSBI.leftShift(JSBI.BigInt(1), JSBI.BigInt(192)); const quoteAmount = FullMath.mulDivRoundingUp(ratioX192, baseAmount, shift); console.log(`${inputAmount} USDC: `, (quoteAmount.toString() / (10 ** quoteTokenDecimals)), 'WETH'); console.log(`${inputAmount} WETH: `, inputAmount / (quoteAmount.toString() / (10 ** quoteTokenDecimals)), 'USDC'); } const fee = 100; const amount = 1; main(amount, 6, 18, fee); But, the result neither matches with the pricing of the Swap nor with the pricing of the Add Liquidity.
So, how to calculate the prices with precision that Uniswap V3 is using both in case of Swap and Add Liquidity, and how the factors like price range (i.e., given as a selection in the UI of Add Liquidity) contribute in this calculation ?
Thanks.

