Convert erc20 baalnce to wei

hey there. I am trying to convert the balance of the erc20 token to wei. How can i do so ?

Array(3) [ {…}, {…}, {…} ]
​
0: Object { token_address: "0x471c3a7f132bc94938516cb2bf6f02c7521d2797", name: "LUNA 2.0 (lunav2.io)", symbol: "LUNA 2.0 (lunav2.io)", … }
​​
balance: "250457000000000000000000"
​​
decimals: 18
​​
logo: null
​​
name: "LUNA 2.0 (lunav2.io)"
​​
symbol: "LUNA 2.0 (lunav2.io)"
​​
thumbnail: null
​​
token_address: "0x471c3a7f132bc94938516cb2bf6f02c7521d2797"
​​
<prototype>: Object { … }
​
1: Object { token_address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", name: "USD Coin", symbol: "USDC", … }
​
2: Object { token_address: "0xdac17f958d2ee523a2206206994597c13d831ec7", name: "Tether USD", symbol: "USDT", … }
​​
balance: "25305020"
​​
decimals: 6
​​
logo: "https://cdn.moralis.io/eth/0xdac17f958d2ee523a2206206994597c13d831ec7.png"
​​
name: "Tether USD"
​​
symbol: "USDT"
​​
thumbnail: "https://cdn.moralis.io/eth/0xdac17f958d2ee523a2206206994597c13d831ec7_thumb.png"
​​
token_address: "0xdac17f958d2ee523a2206206994597c13d831ec7"
​​
<prototype>: Object { … }
​
length: 3
​
<prototype>: Array []

You can use moralis units for conversion.
This is an example of converting 0.5 erc20 token to wei
Moralis.Units.Token("0.5", "18")
https://docs.moralis.io/moralis-dapp/tools/moralis-units#converting-erc20-token-to-wei

1 Like

Besides the possibility of using Moralis API, you could also code an algorithm to reduce connections with the API.

If you want to convert wei to erc20 token
token_balance = wei_balance / (10**token_decimals)

If you want to convert erc20 token to wei
wei_balance = (10**token_decimals) * token_balance

I hope this will help you

Using the Units is not using the API, requests are related to APIs whereas no request is related to the Units. They’re implied to make the work easier to read and understand and work with.
Full explanation here https://docs.moralis.io/moralis-dapp/tools/moralis-units

Oh, I didn’t know that. Thanks!

Thank you guys :clap::+1::heart:.
Will try

what do i need to do to convert from a erc20 balance to eth ?

You need to get the token price in eth https://docs.moralis.io/moralis-dapp/web3-api/token#gettokenprice, and then multiply the balance unit with the nativePrice value

1 Like