0

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?

2
  • The error is quite clear amounts[1].div is not a function. You are calling a function div from amounts[1] that doesn't exist. From the logged data it seems is returning strings instead of numbers.
    – Ismael
    Aug 8 at 3:18
  • 1
    Thank you! It worked. I had to convert the string to a number then convert it back to a string when calling the swap function. What confused me is that I watched a video and the creator did not convert amounts[1] to a number in his code, so I figured the sub and div functions were able to do this percent calculation on strings. Thanks again. Aug 8 at 13:58
1

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'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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