Getting correct decimals in ethers.io library, using getAmountsOut() ABI

2.7k Views Asked by At

I am using getAmountsOut() interface to get the current PancakeSwap price of a random BSC token.

The digits I get back do match Pancakeswap's quote (roughly), but I seem to be unable to display it in a human-readable format with the correct decimals.

import ethers from "ethers";

// ...open factory, account etc....

const TOKEN_WBNB_ADDR = "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"; // WBNB
const TOKEN_FEG_ADDR = "0xacfc95585d80ab62f67a14c566c1b7a49fe91167"; // Token
const router = new ethers.Contract(
    factory,    // PancakeSwap V2 factory
    ['function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)'],
    account,
);

// how many WBNBs would we get for 1 FEG?
const wbnbsPerToken = await router.getAmountsOut(
    ethers.utils.parseUnits("1.00", 9), // token has 9 decimals
    [TOKEN_FEG_ADDR, TOKEN_WBNB_ADDR]);

console.log(`${ethers.utils.formatUnits(wbnbsPerToken[1], 9)} WBNB per FEG`);

// My script's output:   0.018870301 WBNB per FEG
// PancakeSwap's output: 0.0000000000190529 WBNB per FEG

Question 1: Ignoring the slight price difference, why are my decimals off so bad (by 9)?

Question 2: Why do I have a price difference? Something with slippage? Pancakeswap's quotes of that coin are consistently a bit higher. It's not a timing thing, it's consistent.

Or am I calculating the quote wrong altogether??

Thanks a bunch in advance!

1

There are 1 best solutions below

0
On

As far as I know, WBNB has 18 decimals, similar to WETH. Change all of your code with ethers.utils.parseUnits("1.00", 9) to

ethers.utils.parseUnits("1.00", 18);

or

ethers.utils.parseUnits('1.00', 'ethers');

and you will be fine.