Ethers.js – Handling GetAmountsOut Returning [object Promise]

ethers.js

I am trying to get the amount out of a token using node.js.

I have imported ethers and run the following code.

const ethers = require('ethers');

const addresses = {
  router: '0x10ED43C718714eb63d5aA57B78B54704E256024E',
}

const router = new ethers.Contract(
  addresses.router,
  [
    'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)'
  ],
);

tokenIn = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c'; 
tokenOut = '0x126f5f2a88451d24544f79d11f869116351d46e1';

const amountIn = ethers.utils.parseUnits('0.1', 'ether');
const amountsOut = router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
  console.log(`
    tokenOut: ${amountsOut.toString()}
`);

I get the following error

tokenOut: [object Promise]
(node:8556) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'call' of null

Im guessing its either something to do with trying to call outside of an async function. How can I use getAmountsOut to get an estimate of tokens returned before swapping? thanks

Best Answer

In case this is still unanswered, you can do the following:

// ... previous code
const amountIn = ethers.utils.parseUnits('0.1', 'ether');

// put the asynchronous stuff and it's dependent code inside an IIFE
(async() => {
  const amountsOut = router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
  console.log(`
    tokenOut: ${amountsOut.toString()}
`);
})();

  

Related Topic