Moralis Units

Intro

All crypto transactions are made in the smallest value - Wei. But to improve the user experience, on the frontend the transfer amounts are usually inputed in an ETH style. Users want to input value 0.0001 TokenA instead of 100000000000000 Wei TokenA. Standard web3 methods are inconvenient for easy converting. The most convenient conversion method is to use the Moralis.Units helper functions.
Wei is the smallest denomination of ether, and you should always make calculations in Wei and convert only for display reasons.

Converting ERC20 Token to Wei

To convert ERC20 token to Wei, you need to specify the amount of tokens and number of decimals.
1
//Example: We want to convert 0.5 BUSD. It has 18 decimals
2
const busdInWei = Moralis.Units.Token("0.5", "18")
3
// expected output: 500000000000000000 Wei
Copied!
The number of decimals for a token can normally be found on Etherscan, on the website of the project or from Moralis API.

Converting Native Asset (ETH/BNB/MATIC etc) to Wei

To convert native asset to Wei, you need to specify the amount of native crypto.
1
//Example: We want to convert 0.5 ETH to Wei
2
const ethInWei = Moralis.Units.ETH("0.5")
3
// expected output: 500000000000000000 Wei
Copied!

Converting token value from Wei

All token values are shown in Wei. If you want to display token values in the "Eth" style, you can use:
1
//Convert token value to ETH style with 6 decimals
2
const tokenValue = Moralis.Units.FromWei("2000000000000000000", 6)
3
​
4
//Convert token value to ETH style with 18 decimals
5
//If you do not specify decimals, 18 decimals will be automatically used
6
const tokenValue = Moralis.Units.FromWei("2000000000000000000")
Copied!
Note that this function is not available in the cloud code yet. You can use it in the SDK only. We are very soon adding it to the cloud code.
Web3 API responses for token balances have decimals and balance in Wei fields:
1
{
2
"token_address": "0x...b0",
3
"name": "name",
4
"symbol": "NAME",
5
"logo": null,
6
"thumbnail": null,
7
"decimals": "18",
8
"balance": "2000000000000000000"
9
},
Copied!
Wei is the smallest denomination of ether, and you should always make calculations in Wei and convert only for display reasons.
Last modified 2mo ago