Source
https://github.com/dialecticch/router
Overview
Simple router to exchange tokens for best price for any UniswapV2 like AMM. This contract can only be used for exchanges that uses the code of Uniswapv2 .
SwapRouterMock
swap
Returns SwapRouter.swap function.
swap in SwapRouter library
Parameters
-
swapsis the candidates of exchanges that we can choose. -
pathis the array of token address which we will use for swap. -
amountis the amount of token we want to sell. -
slippageis the max slippage in basis points.
-
Find the best profitable exchange and the corresponding
amountOutfor givenamountby usingdataForBestExchangefunction.
(UniswapV2 swap, uint256 amountOut) = dataForBestExchange(swaps, path, amount); -
Approve
swap(exchange we choose) to usepath[0](input token for swap) foramount.
ERC20(path[0]).approve(address(swap), amount); -
Swap the token using
swapExactTokensForTokensfunction from the exchange address.outis the real amount of output token we receive.
uint256[] memory amountsOut = swap.swapExactTokensForTokens( amount, (amountOut * (1000 - slippage)) / 1000, path, address(this), block.timestamp + 180 ); uint256 out = amountsOut[amountsOut.length - 1];
dataForBestExchange
Returns the best exchange and the corresponding output value.
For given swap, we calculate the biggest out value by using amountOutFor function.
for (uint256 i = 0; i < length; i++) {
uint256 out = amountOutFor(swaps[i], path, amount);
if (out > bestAmount) {
bestExchange = swaps[i];
bestAmount = out;
}
}
amountOutFor
Use getAmountsOut function to calculate the optimal output value from given amountIn and path.
try exchange.getAmountsOut(amountIn, path) returns (uint256[] memory amountsOut) {
return amountsOut[amountsOut.length - 1];
} catch {
return 0;
}
Top comments (0)