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)
Best Answer
So it looks like you read the "sqrtPriceX96" by querying the "slot0" function on the pair contract, then you call the "swap" method on the pair contract. this takes recipient, a true or false which indicated which way you are swapping, the amount, and the "sqrtPriceX96". It also looks like they have a "Quoter" contract that gives you the amount out for the frontend I assume.
Here are some links to the new interfaces:
pool read fuctions: https://docs.uniswap.org/protocol/reference/core/interfaces/pool/IUniswapV3PoolState#slot0
pool write functions: https://docs.uniswap.org/protocol/reference/core/interfaces/pool/IUniswapV3PoolActions#swap
quoter functions: https://docs.uniswap.org/protocol/reference/periphery/interfaces/IQuoter