EatTheBlocks Forum

Trouble swapping from token to ETH with Uniswap contract

Hi, I’m working on a flash-loan project, and the first step is to test swapping out swapping tokens on Uniswap.

I found your Youtube tutorial and was successful in swapping ETH to DAI on Kovan network.

However, when I try to swap back from DAI to ETH, the contract keeps failing. Would you mind taking a look at the contract and seeing what I’m doing wrong? Thanks!

 function buyAndSellFromUniswap(uint256 _amount) public {
        //Buy DAI from uniswap then swap it back to ETH
        address kovanFactoryAddress = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30;
        address kovanUniswapDAI = 0x4C38cDC08f1260F5c4b21685654393BB1e66a858;
        UniswapFactoryInterface uniswapFactory = UniswapFactoryInterface(kovanFactoryAddress);
        UniswapExchangeInterface uniswapExchange = UniswapExchangeInterface(uniswapFactory.getExchange(kovanUniswapDAI));
        uint tokensToBuy = uniswapExchange.getEthToTokenInputPrice(_amount);
        uint256 boughtTokens = uniswapExchange.ethToTokenSwapInput.value(_amount)(
        uint minEth = uniswapExchange.getTokenToEthInputPrice(boughtTokens);
        //Approving uniswapExchange to spend DAI
       uint256 boughtEth = uniswapExchange.tokenToEthSwapInput(
            boughtTokens, //Usually is around 7223443973950054616
            minEth,  //Usually around 994037339528957731

I’m sure it’s something simple, but since the EVM gives terrible error messages, it’s been blocking me all afternoon!

You need to comment out the code little by little until you see the error appearing. This way you know what’s the exact line that is causing problem. My guess is that you don’t approve enough tokens.

By the way no need to cast boughtTokens to uint, it already has this type. uint256 is just the long-hand syntax for uint.