I am using the getAmountsOut() interface to get the current PancakeSwap price of a random BSC token that has 9 decimals in its smart contract, see https://bscscan.com/token/0xacfc95585d80ab62f67a14c566c1b7a49fe91167#readContract
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!