Convert amount
Overview
When creating transactions, you need to represent token amounts using hexadecimal strings rather than regular strings. This guide walks you through the conversion process.
Convert amount
- JS
- Unity
The convertAmount
function converts a string representation of a number (amount
) returns a BigNumber representation, using the specified decimals
to determine the number of decimal places::
import { BigNumber, parseFixed } from "@ethersproject/bignumber";
const convertAmount = (amount, decimals) => {
const rawAmount = parseFixed(amount, decimals);
return rawAmount;
};
For example, let's convert 10 RON to HexString:
- Start with the token amount as a string:
const amount = "10";
- Convert to BigNumber for precision:
import { BigNumber, ethers } from "ethers";
const amount = "10";
const rawAmount = convertAmount(amount, 18); // Precision set to 18 decimals
- Transform BigNumber to HexString for transaction usage:
import { BigNumber, ethers } from "ethers";
const amount = "10";
const rawAmount = convertAmount(amount, 18);
const hexAmount = ethers.utils.hexValue(rawAmount);
The MPCUtils.ConvertAmount
method converts a string representation of a number (amount
) and returns a BigInteger representation, using the specified power
to determine the number of decimal places:
BigInteger MPCUtils.ConvertAmount(string amount, int power);
After that, the BigIntToHex
method converts the big integer representation to HexString:
var hexValue = bigInt.BigIntToHex();
For example, let's convert 10 RON to HexString:
- Start with converting the string amount to BigInteger for precision:
var amount = MPCUtils.ConvertAmount("10", 18);
Debug.Log($"BigInteger amount: {amount}");
- Transform BigInt to HexString for transaction usage:
var amount = MPCUtils.ConvertAmount("10", 18);
Debug.Log($"Hex amount: {amount.BigIntToHex()}");
Was this helpful?
Happy React is loading...