0

I have the amount of transfered tokens converted from a transactionreceipts log data.

for example USDT the value I got is 500000000 , USDT has 6 decimals. The actual transfered value is only 500 USDT, how can I convert that using web3 or javascript to use the contracts decimals and output the correct value?

Would amount / math.pow(10, tokendecimals) be the correct way to do this?

Regards

2 Answers 2

1

you should use a library like ethers.js https://docs.ethers.io/v4/api-utils.html

utils . parseUnits ( valueString , decimalsOrUnitName ) => BigNumber Parse the valueString representation of units into a BigNumber instance of the amount of wei. The decimalsOrUnitsName may be a number of decimals between 3 and 18 (multiple of 3) or a name, such as gwei.

utils . formatUnits ( wei , decimalsOrUnitName ) => string

0

I built a simple tool that does this, called evm-bn. Here's how you could use it to format 500 USDT:

import { BigNumber } from "@ethersproject/bignumber";
import { toBn, fromBn } from "evm-bn";

const decimals : Number = 6;

const amount : BigNumber = fromBn("500000000", decimals) // amount = "500"

const amount2 = toBn("500", decimals) // amount2.toString() = "500000000" 

The evm stands for Ethereum Virtual Machine, while bn for "big number". The second parameter is optional; it defaults to 18 decimals.

Note that this was designed to be used alongside @ethersproject/bignumber. The ethers package is a peer dependency.

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.