0

I am using this simple code to get wallet balance of USDC. I am not sure how I can convert wei value to proper value. Let's say I have 1,076.235541 USDC in wallet. The below code shows 1076235541 and 0.000000001076235541. But I need to get value 1076 from it.

    const minABI = [
      // balanceOf
      {
        constant: true,
        inputs: [{ name: "_owner", type: "address" }],
        name: "balanceOf",
        outputs: [{ name: "balance", type: "uint256" }],
        type: "function",
      },
    ];
    const tokenAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
    const walletAddress = MY_WALLET_ADDRESS;

    const contract = new Web3Client.eth.Contract(minABI, tokenAddress);

    async function getBalance() {
      const result = await contract.methods.balanceOf(walletAddress).call();
      const format = Web3Client.utils.fromWei(result); 
      console.log(result);
      console.log(format);
    }

2 Answers 2

2

The fromWei function converts from wei to ether, meaning it divides the number by 1e18.

ERC20 tokens allows a custom decimal point precision, USDC specifically uses 6 decimal precision. So you just need to divide your result by 1e6 -

const balance = parseInt(result) / 10**6;

But ideally, to support any ERC20 token, read the number of decimals from the contract and use that; also better use a library that knows how to work with big numbers, because JS has issues when it comes to big/real numbers.

async function getBalance() {
   const result = await contract.methods.balanceOf(walletAddress).call();
   const decimals = await contract.methods.decimals().call();
   const balance = new BigNumber(result).div(10 ** decimals);
   return balance;
}
1
  • Hey, where you imported the BigNumber object from? Is it bignumber.js or what?
    – VitoCK
    Commented Jul 7 at 10:12
0

One ETH is 10"18 wei.

So when you transfer 1ETH you actually transfer 10"18 wei. All because one ETH has 18 decimal places.

USDC, on other hand, has 6 decimal places. (Same as todays banks that will calculate money up to the 6'th digit)

So to transfer 1USDC, you actually transfer 1 000 000 of its token's wei equivalent.

(That is if the numbers you gave me here are alright).

2
  • So I can simply devide number with javascript by 1000000 and it will be fine, is that the way of doing it? The same also for usdt and dai? const result = await contract.methods.balanceOf(walletAddress).call(); balance = result/1000000
    – JohnyFree
    Commented May 3, 2022 at 17:38
  • 1
    Yeah, (do test it first). But for example, I do the same with ERC20 tokens (I devide it by 10"18)
    – Sky
    Commented May 3, 2022 at 19:32

Your Answer

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

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