I've been able to do swaps through Uniswap's peripheral smart contract Router 02 by calling any of the functions such as:
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
However, none of these functions has any field referring to the slippage (amount the price moves in a trading pair between when a transaction is submitted and when it is executed), and I don't know exactly at which stage the slippage is set before launching the swap transaction.
Is there any way to handle the slippage tolerance programatically when executing a swap transaction?
Best Answer
Yes, you can adjust it with that function.
The Uniswap router swap functions trade asset A for asset B, with slippage. Mostly they are of type "give A, get B, while either the amount of A or B remains static". So you for example have a swap "I want to pay x amount of A tokens and get as many B tokens as possible" or "I want to pay as few A tokens as possible and get x amount of B tokens".
In your case you are using a function which gives a minimum amount of tokenA and gets a certain numbers of tokenB out. So the
amountOut
is a static number which you define, andamountInMax
is the maximum you are willing to input tokens A to get the static amount of tokens B.So your slippage is defined by
amountInMax
.