function swapTokensV2( address user, address router, address tokenIn, uint256…
- User
function swapTokensV2( address user_, address router_, address tokenIn_, uint256 amountInTokens_, address tokenOut_ ) external payable whenNotPaused { if (tokenIn_ == address(0) || tokenOut_ == address(0)) revert CommonError("Token in or out zero address.");
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(router_); if (uniswapV2Router.WETH() == address(0)) revert CommonError("Invalid router address"); address msgSender = msg.sender; uint256 msgValue = msg.value; IERC20_EXT ierc20 = IERC20_EXT(tokenIn_); uint256 balanceBefore; if (tokenIn_ == weth) { require( _tokensToWei(amountInTokens_, ierc20.decimals()) == msgValue, "ETH value must be equal to amountInTokens_" ); balanceBefore = address(this).balance; } else { ierc20.safeTransferFrom(msgSender, address(this), amountInTokens_); balanceBefore = ierc20.balanceOf(address(this)); } StructUser storage userAccount = _mappingStructUser[user_]; ierc20.approve(router_, amountInTokens_); address[] memory path = new address[](2); path[0] = tokenIn_; path[1] = tokenOut_; uint256[] memory amounts = uniswapV2Router.swapExactTokensForTokens( amountInTokens_, 0, path, msgSender, block.timestamp + 60 ); uint256 balanceAfter = IERC20(tokenIn_).balanceOf(address(this)); uint256 leftover = balanceAfter - balanceBefore; if (leftover > 0) { ierc20.safeTransfer(msgSender, leftover); } uint256 newPrice = calculateCurrentPrice(tokenIn_, amounts[0]); emit TokenSwapped( msgSender, tokenIn_, amountInTokens_, amounts[1], newPrice ); }swap eth to token if in currency is eth
- Assistant