Web3j and Uniswap Router V2, converting wei to uint256

1.8k views Asked by At

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:

  • try and convert the amount to uint256, trailing zeros and all (not sure how though)
  • look at how the frontend is doing it, not sure if I should call swapExactETHForTokens directly, without calling some other function before

So some questions would be:

  • how can I turn lets say a value of 1 ETH to a BigInteger representing that uint256 number?
  • should I call other functions beforehand?
  • how do I set the gas? I guess through the new DefaultGasProvider()
  • I saw that in Javascript they do something like const MIN_TOKENS = web3.utils.toHex(0.2 * 10 ** 18), how can I do this in Web3 without being hackish and add trailing zeros?
1

There are 1 answers

0
Sorin Grecu On BEST ANSWER

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.