Last active
May 11, 2022 21:53
-
-
Save kalloc/ad1746503ddf076fce22e0676f8a8199 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity >=0.8.9; | |
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; | |
contract Test { | |
address[] public routers; | |
address[] public connectors; | |
/** | |
Gets router* and path* that give max output amount with input amount and tokens | |
@param amountIn input amount | |
@param tokenIn source token | |
@param tokenOut destination token | |
@return amountOut — max output amount and router and path, that give this output amount | |
router* - Uniswap-like Router | |
path* - token list to swap | |
*/ | |
function quote( | |
uint amountIn, | |
address tokenIn, | |
address tokenOut | |
) external view returns (uint amountOut, address router, address[] memory path) { | |
path = new address[](2); | |
path[0] = tokenIn; | |
path[1] = tokenOut; | |
for(uint i; i<routers.length;i++) { | |
uint amount = this.quoteForRouter(routers[i], amountIn, path); | |
if (amount > amountOut) { | |
amountOut = amount; | |
router = routers[i]; | |
} | |
} | |
} | |
function quoteForRouter(address router, uint amountIn, address[] memory path) view public returns (uint256 amountOut) { | |
uint[] memory amounts = IUniswapV2Router02(router).getAmountsOut(amountIn, path); | |
amountOut = amounts[amounts.length - 1]; | |
} | |
/** | |
Swaps tokens on router with path, should check slippage | |
@param amountIn input amount | |
@param amountOutMin minumum output amount | |
@param router Uniswap-like router to swap tokens on | |
@param path tokens list to swap | |
@return amountOut actual output amount | |
*/ | |
function swap( | |
uint amountIn, | |
uint amountOutMin, | |
address router, | |
address[] memory path | |
) external returns (uint amountOut) { | |
require(amountOutMin > 0, "Amount out too low"); | |
uint[] memory amounts = IUniswapV2Router02(router).swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 5); | |
amountOut = amounts[amounts.length - 1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment