receive() external payable {}
function swapEthForTokens(uint256 ethAmount) public payable returns (uint256) {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(this);
uint[] memory tokenAmount_ ;
// make the swap
tokenAmount_ = uniswapV2Router.swapExactETHForTokens{ value: ethAmount }(
0,
path,
address(this), // The contract
block.timestamp
);
uint256 outputTokenCount = uint256(tokenAmount_[tokenAmount_.length - 1]);
return outputTokenCount;
}
exmple
if inside my contract have remain ETH
I would like my contract to use all remaining ETH to token
after i add liquidity and swap token no problem but when i deposit eth to my contract and swap i got error
" The transaction cannot succeed due to error: undefined. This is probably an issue with one of the tokens you are swapping. "
Best Answer
The general method I use for my contracts is as such:
This function simply swaps amount of inputted WETH in the contract for tokens (assuming an ERC20 contract). If we wanted to swap everything I suggest writing a separate function:
Also, it is generally good practice to keep functions like this private.