0

I'm trying to create a split swap smart contract. This contract works fine on the BSC chain, but on ETH I got the error "TransferHelper: TRANSFER_FROM_FAILED", why?

SplitSwap.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;

import '@uniswap/v2-core/contracts/interfaces/IERC20.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';

contract SplitSwap {

    function splitSwap(address token0, address token1, address router, uint256 amount, uint256 size) public {

        IERC20(token0).transferFrom(msg.sender, address(this), amount);

        IERC20(token0).approve(router, amount);
        
        address[] memory paths = new address[](2);

        paths[0] = token0;
        paths[1] = token1;

        while (amount > 0) {

            uint amountIn = amount < size ? amount : size;
            uint amountOut = 0;

            IUniswapV2Router02(router).swapExactTokensForTokens(
                amountIn, 
                amountOut, 
                paths, 
                msg.sender,
                block.timestamp + 120);

            amount = amount - amountIn;
        }  
    }
}

1 Answer 1

0

The first mistake that comes to mind is that the contract doesn't approve the tokens for the router. The router needs to transfer the tokens from the caller, so you need to approve it:

IERC20(token0).approve(router, size);

You also need to make sure it's the contract that holds the token and not your wallet.

1
  • I updated code, can you check?
    – Brain King
    Commented Mar 23 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.