1

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!

1
  • Thank you, your question inspired me a lot. Feb 9, 2022 at 13:07

1 Answer 1

0

You are trying to change a 9 decimals token (FEG) into a 18 decimal tokens (WBNB - https://bscscan.com/token/0x11ba25374933cec65f1dc6c4fb6b8f25fc924130). You should be using the parseUnits function with the decimals of the target token.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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