Uniswap – Fix TypeError: Member ‘WETH’ Not Found in contract IUniswapV2Router

cpp-ethereumuniswap

My code below

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IUniswapV2Router {
    function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts);
    function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
}

contract MEVBot {
    address private constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Mainnet Uniswap V2 Router Address
    address private constant tokenToTrade =0xe945485c8F4b60c96Fa14f9D403ef76cBc29b0Fb; // Replace with the token address to trade
    uint private constant slippage = 5; // Custom slippage of 5%
    uint private constant maxTradingAmount = 1 ether; // Maximum amount of ETH to trade at once
    uint private constant maxTradingFee = 0.01 ether; // Maximum trading fee in ETH

    receive() external payable {}

    function start() public {
        address[] memory path = new address[](2);
        path[0] = IUniswapV2Router(uniswapRouter).WETH();
        path[1] = tokenToTrade;

        uint[] memory amounts = IUniswapV2Router(uniswapRouter).getAmountsOut(maxTradingAmount, path);
        uint expectedAmountOut = amounts[1] - (amounts[1] * slippage / 100);

        require(expectedAmountOut > maxTradingFee, "Trading fee is higher than expected profit");

        IUniswapV2Router(uniswapRouter).swapExactETHForTokens{value: maxTradingAmount}(expectedAmountOut, path, address(this), block.timestamp);

        // Wait for some time for the token price to increase
        // Sell the token for profit and withdraw the funds
        // ...
    }

    function stop() public {
        // Stop the bot from buying and selling tokens
        // ...
    }

    function withdraw() public {
        // Withdraw the funds from the bot
        // ...
    }
}

Best Answer

It appears that you may have made a mistake while importing the Uniswap interface in your smart contract. To import the interface correctly, you should include the following code at the beginning of your contract:

import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

Once you have imported the interface, you can use it in your contract code. For example, to obtain the WETH address, you can use the following code:

path[0] = IUniswapV2Router02(uniswapRouter).WETH();

Hope that helps!

Related Topic