am using Uniswap V3: Router 2 swapExactTokensForTokens to make simple swaps, eg swap usdc to weth.
The issue am facing is in every and each example found online amountOutMin is defined to 0 , which allows 100% slippage and is not good.
encodeFunctionData("swapExactTokensForTokens",[ammount,"0",[token,"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"],public_key])
I have not found solution for this that would not require me to use uniswap sdk. Which is pointless since am doing this in pure js.
- note ammount is in token native decimal
To do this you need to:
- Query the right pool from uniswap factory 0x1F98431c8aD98523631AE4a59f267346ea31F984 , use 1% fee (10000)
- Query price from the pool using the slot0 function, this returns price
- price = (sqrtPriceX96 ** 2 / 2 ** 192)
- min_received = (ammount*(sqrtPriceX96 ** 2 / 2 ** 192))*0.9 (for 10% slippage)
- this should return value in decimals of token you are trying to swap to This works but not for tokens with 6 decimals ? huh
Am i missing smt ?
For example in this pool the price should equal 820000000000000wei which is 0.00082 or 1USD at the time
https://etherscan.io/address/0xC5aF84701f98Fa483eCe78aF83F11b6C38ACA71D#readContract
But it equals 1.2235422586602433e-9 or 0.0000000012235422586602433
is this issue in fetching the pool in first place or i need to add decimals calculation
SOLUTION:
-check token0 in given pool, if it is the currency you want output in, use:
2 ** 192 / sqrtPriceX96 ** 2 * 10 ** (decimals1-decimals0)
-if token 1 is currency you want output in, use:
sqrtPriceX96 ** 2 / 2 ** 192 * 10** (decimals1-decimals0)