0

I'm working on a TypeScript/JavaScript project where I'm using the UniswapV2Router for token swapping on the Ethereum network. However, I'm encountering an issue with the code, specifically with the swapTokens3 function. It's giving me the error message "uniswapv2router: excessive_input_amount."

Here's the relevant code snippet:

async function swapTokens3(
  tokenToSell: Token,
  tokenToBuy: Token,
  amount: string,
  slippage = 50
) {
  try {
    const UNISWAP_ROUTER_CONTRACT = new ethers.Contract(
      UNISWAP_ROUTER_ADDRESS,
      UNISWAP_ROUTER_ABI,
      wallet
    );
    const pair = await Fetcher.fetchPairData(
      tokenToSell,
      tokenToBuy,
      provider
    );

    checkLiquidity(pair.liquidityToken.address);
    const tokenA = new ethers.Contract(
      tokenToSell.address,
      erc20Abi,
      wallet
    );

    const tokenB = new ethers.Contract(
      tokenToBuy.address,
      erc20Abi,
      wallet
    );

    const tokenBalance = await tokenA.balanceOf(wallet.address);
    const tokenBalance2 = await tokenB.balanceOf(wallet.address);
    console.log(
      'Token balance:' +
        ethers.utils.formatEther(tokenBalance) +
        '\n' +
        'Token balance2:' +
        ethers.utils.formatEther(tokenBalance2)
    );

    const route = new Route([pair], tokenToBuy);
    const amountOut = ethers.utils.parseEther(amount).toString();

    const slippageTolerance = new Percent(
      slippage.toString(),
      '10000'
    );

    const trade = new Trade(
      route,
      new TokenAmount(tokenToBuy, amountOut),
      TradeType.EXACT_INPUT
    );

    const amountInMax = trade
      .maximumAmountIn(slippageTolerance)
      .raw.toString();

    const amountInMaxHex =
      ethers.BigNumber.from(amountInMax).toHexString();

    const path = [tokenToSell.address, tokenToBuy.address];
    const to = wallet.address;
    const deadline = Math.floor(Date.now() / 1000) + 60 * 20;

    const approval = await tokenA.approve(
      UNISWAP_ROUTER_CONTRACT.address,
      amountInMaxHex
    );

    await approval.wait();

    const rawTxn =
      await UNISWAP_ROUTER_CONTRACT.populateTransaction.swapTokensForExactETH(
        amountOut,
        amountInMaxHex,
        path,
        to,
        deadline,
        {
          gasLimit: 300000,
          gasPrice: ethers.utils.parseUnits('5', 'gwei'),
        }
      );

    //Returns a Promise which resolves to the transaction.
    let sendTxn = (await wallet).sendTransaction(rawTxn);

    //Resolves to the TransactionReceipt once the transaction has been included in the chain for x confirms blocks.
    let reciept = (await sendTxn).wait();

    //Logs the information about the transaction it has been mined.
    if (reciept) {
      console.log(
        (await sendTxn).hash +
          '\n' +
          'Block Number: ' +
          (await reciept).blockNumber +
          '\n' +
          'Navigate to https://rinkeby.etherscan.io/txn/' +
          (await sendTxn).hash,
        'to see your transaction'
      );

      const tokenBalance = await tokenA.balanceOf(wallet.address);
      const tokenBalance2 = await tokenB.balanceOf(wallet.address);
      console.log(
        'Token balance:' +
          ethers.utils.formatEther(tokenBalance) +
          '\n' +
          'Token balance2:' +
          ethers.utils.formatEther(tokenBalance2)
      );
    } else {
      console.log('Error submitting transaction');
    }
  } catch (e: any) {
    console.log(e.message);
  }
}

const ETH = new Token(
    UNISWAP.ChainId.GÖRLI,
    address0,
    decimals0,
    symbol0,
    name0
  );

  const DAI = new Token(
    UNISWAP.ChainId.GÖRLI,
    address3,
    decimals3,
    symbol3,
    name3
  );

  swapTokens3(DAI, ETH, '100');

Here's what I'm trying to achieve:

I want to swap a specific amount of one ERC-20 token (e.g., DAI) for another token (e.g., ETH) on the Ethereum network. I'm setting a slippage tolerance of 50 basis points (0.5%).

The error occurs when I call the swapTokensForExactETH method on the Uniswap router contract. I've double-checked my token balances and approvals, but I can't seem to figure out why I'm getting this "excessive_input_amount" error.

Any insights into what might be causing this error or how I can resolve it would be greatly appreciated. Additionally, if there are any best practices or common pitfalls related to using the UniswapV2Router in TypeScript/JavaScript, I'd like to know about them.

Thank you in advance for your help!

2 Answers 2

1

I don't use js but unless that is the way your function is coded, that isn't how slippage setting works for v2, "50 basis points".

Setting amountOutMin would be saying that you will accept as little as 50 of the output token, not 50.0 but 0.000000000000000050 of a token with 18 decimals like dai or eth.

Setting amountInMax to 50 would be saying that 0.000000000000000050 is the max amount you willing to pay.

You can recreate the error UniswapV2Router: EXCESSIVE_INPUT_AMOUNT by using too low an amountInMax.

So would look at that.

0

After investigating the issue further, I was able to resolve the "uniswapv2router: excessive_input_amount" error in my code. The key changes I made include:

  1. I used the swapExactTokensForETH function instead of swapTokensForExactETH.
  2. I removed the conversion of amounts to hex format.
  3. I added an approval transaction for the token.

Here's the updated code for the sellTokens function:

async function sellTokens(tokenToSell: Token, amount: string, slippage = "50") {
try {
    const pair = await Fetcher.fetchPairData(ETH, tokenToSell, provider);

    const tokenA = new ethers.Contract(
        tokenToSell.address,
        [
            "function approve(address _spender, uint256 _value) public returns (bool success)",
            "function allowance(address _owner, address _spender) public view returns (uint256 remaining)",
            "function balanceOf(address _owner) public view returns (uint256 balance)",
        ],
        wallet,
    );

    const route = new Route([pair], tokenToSell);

    const amountIn = ethers.utils.parseEther(amount).toString();

    const slippageTolerance = new Percent(slippage, "10000");

    const trade = new Trade(
        route,
        new TokenAmount(tokenToSell, amountIn),
        TradeType.EXACT_INPUT,
    );

    const amountOutMin = trade
        .minimumAmountOut(slippageTolerance)
        .raw.toString();

    const path = [tokenToSell.address, ETH.address];
    const to = wallet.address;
    const deadline = Math.floor(Date.now() / 1000) + 60 * 20;

    // Approve the Uniswap router to spend the token
    const approveTxn = await tokenA.approve(
        UNISWAP_ROUTER_ADDRESS,
        amountIn,
    );

    await approveTxn.wait();

    // Swap tokens using swapExactTokensForETH
    const rawTxn =
        await UNISWAP_ROUTER_CONTRACT.populateTransaction.swapExactTokensForETH(
            amountIn,
            amountOutMin,
            path,
            to,
            deadline,
            {
                gasLimit: 300000,
                gasPrice: ethers.utils.parseUnits("5", "gwei"),
            },
        );

    let sendTxn = wallet.sendTransaction(rawTxn);

    let receipt = (await sendTxn).wait();

    if (receipt) {
        console.log(
            (await sendTxn).hash +
                "\n" +
                "Block Number: " +
                (await receipt).blockNumber +
                "\n" +
                "Hash" +
                (await sendTxn).hash,
            "to see your transaction",
        );
    } else {
        console.log("Error submitting transaction");
    }
} catch (e: any) {
    console.log(e.message);
}

}

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.