JavaScript Uniswap React – Troubleshooting Errors in Division After Calling getAmountsOut from Uniswap Router 02

javascriptreactuniswap

I am having a lot of problems implement a swap via metamask using the uniswap router 02. I am able to call the getAmountsOut function but get an error when trying to do the following:

const getAmountOutMin = async () => {
                const amounts = await quickswap.methods.getAmountsOut(amountIn, [baseContract, targetContract]).call();
                console.log(amounts)
                setAmountOutMin(amounts[1].sub(amounts[1].div(10)));
                console.log(amountOutMin)
            }

I get the following error:

Unhandled Rejection (TypeError): amounts[1].div is not a function
getAmountOutMin
  133 |     const amounts = await quickswap.methods.getAmountsOut(amountIn, [baseContract, targetContract]).call();
  134 |     console.log(amounts)
  135 |     //Our execution price will be a bit different, we need some flexbility
> 136 |     setAmountOutMin(amounts[1].sub(amounts[1].div(10)));
      | ^  137 |     console.log(amountOutMin)
  138 | }
  139 | getAmountOutMin();

When I log the value of amounts in the console I get this:

[
    "1000000000000000000",
    "2767484742082040"
]

What am I missing?

Best Answer

Thanks to Ismael for helping solve the issue.

The problem was solved by converting the amounts[1] to a number. Here's what I did and it works:

// in useeffect
const getAmountOutMin = async () => {
                setAmounts(await contract.methods.getAmountsOut(amountIn, [baseAddress, targetAddress]).call()))}
// minimum value is 95% of original
const amountOut1 = (Math.round(Number(amounts[1]) * 0.95)).toString()
// amountOutMin input for swapping functions such as SwapExactETHForTokens
setAmountOutMin(ethers.utils.parseUnits(amountOut1, 'wei'))
Related Topic