javaethereumsmartcontractsweb3-java

Web3j and Uniswap Router V2, converting wei to uint256


the issue I'm having is that I'm trying to send a value in wei to swapExactETHForTokens, but it returns Fail with error 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'. If I convert 1 ETH to wei (in code) it comes out as 1000000000000000000. When doing a swap from the Uniswap GUI it turns 1 ETH to 1059503741842561918508100943433. I'll put my code below, guess I'll look into the Uniswap frontend project to see how it converts the 1 ETH in the GUI to that value (guess it also adds the fees before calling the smart contract)

  web3j = Web3j.build(web3jService);
        UniswapV2Router02 uniSwapRouter = UniswapV2Router02.load(UNISWAP_V2_RINKEBY, 
                web3j, 
                credentials, 
                new DefaultGasProvider());
        uniSwapRouter.swapExactETHForTokens(
                Convert.toWei("1", Convert.Unit.ETHER).toBigInteger(),
                Arrays.asList(WETH_ADDRESS, DAI_ADDRESS),
                credentials.getAddress(),
                BigInteger.valueOf(DEADLINE_TIMESTAMP)).send();

What I will try:

So some questions would be:


Solution

  • Funny how posting a question here helps with rubber ducking, isn't it?

    Looked at the contract and it reads msg.value. Guess what, we're not sending that. Even though the swapExactEthForTokens is a payable, the wrapper isn't generating a parameter for it.

    Follow this bug for more info: https://github.com/web3j/web3j/issues/1268

    I was basically sending a transaction with 0 ether, ofc it returned INSUFFICIENT_INPUT_AMOUNT. Thought that if the Java Wrapper only gave me that first amount it would automatically take care of it but nope.

    What I had to do was manually add the weiValue to executeRemoteCallTransaction(function, weiValue) because the wrapper doesn't do that, look at the above bug report.

    Anyway, I'll leave this open in case anyone wants to chime-in with more insights.