Reputation: 103
I have the following code that swaps ETH (or BNB in may case on the BSC testnet) for a specific token:
pragma solidity 0.7.1;
import "https://github.com/pancakeswap/pancake-swap-periphery/blob/master/contracts/interfaces/IPancakeRouter02.sol";
contract UniswapExample {
address internal constant UNISWAP_ROUTER_ADDRESS = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 ; //Router for pancake
IPancakeRouter02 public uniswapRouter;
//Store addresses
//address[] tokens = new address[](2);
//address private usdt = 0x7ef95a0FEE0Dd31b22626fA2e10Ee6A223F8a684;
//address private busd = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
//address private dai = 0x8a9424745056Eb399FD19a0EC26A14316684e274;
address private crypto1 = 0x7ef95a0FEE0Dd31b22626fA2e10Ee6A223F8a684;
address private crypto2 = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
address private crypto3 = 0x8a9424745056Eb399FD19a0EC26A14316684e274;
//uint totalSum;
constructor() {
uniswapRouter = IPancakeRouter02(UNISWAP_ROUTER_ADDRESS);
}
function convertEthToCrypto(uint cryptoAmount) public payable {
uint deadline = block.timestamp + 15; // using 'now' for convenience, for mainnet pass deadline from frontend!
uniswapRouter.swapETHForExactTokens{ value: msg.value }(cryptoAmount, getPathForETH(crypto1), address(this), deadline);
// refund leftover ETH to user
(bool success,) = msg.sender.call{ value: address(this).balance }("");
require(success, "refund failed");
}
function getPathForETH(address crypto) public view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = uniswapRouter.WETH();
path[1] = crypto;
return path;
}
function getETH() public view returns(address) {
return uniswapRouter.WETH();
}
// important to receive ETH
receive() payable external {}
}
Here the convertEthToCrypto
swaps one token and is a payable function. So in Remix I input a specific amount of WEI and the function swaps the token.
But how do I manage to swap multiple tokens at once?
Upvotes: 0
Views: 2597
Reputation: 66
If I was you, I would use swapExactTokensForTokens and call it as many as you want. you can even create a loop to manage if you have many cryptos to swap or if it's always the same, hardcode the calls. here is a quick example with DAI and USDT. you can replace the tickers with variables and use a loop if you want.
address[] memory path = new address[](2);
path[0] = address(DAI);
path[1] = address(USDT);
UniswapV2Router02.swapExactTokensForTokens(amountIn, amountOutMin, path, msg.sender, block.timestamp);
Upvotes: 1