'Avalanche - eth_getBalance - Converting the balance from hexadecimal to decimal
Context
Using the Avalanche Explorer, I selected a random address that has some AVAX in it:
https://cchain.explorer.avax.network/address/0xB9F79Fc4B7A2F5fB33493aB5D018dB811c9c2f02/transactions
At the time that I looked that address up, the AVAX balance is around 39,166:
Code
I'm using the following REST call to retreive the balance of that address:
curl --location --request POST 'https://api.avax.network/ext/bc/C/rpc' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0xB9F79Fc4B7A2F5fB33493aB5D018dB811c9c2f02",
"latest"
],
"id": 1
}'
At the time that I made the call, it returned the following:
{"jsonrpc":"2.0","id":1,"result":"0x8868dc30a5d07460032"}
Question
As you can see, the balance comes back as:
0x8868dc30a5d07460032
What's the recommended way to convert that to the decimal balance?
Feel free to point me to the right place in the developer documentation if this is discussed there.
Thanks!
Solution 1:[1]
If you are working with Javascript here is the snippet:
async getBalance(address) {
const response = await fetch('https://api.avax.network/ext/bc/C/rpc', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'eth_getBalance',
params: [
address,
'latest'
]
})
});
const data = await response.json();
return parseInt(data.result, 16) / Math.pow(10, 18);
}
You can make the same calculation with other languages or whatever you use.
Solution 2:[2]
It looks like you simply divide by 18.
Here's some PowerShell function Get-AVAX-Balance
that will retrieve a balance given an address:
function Convert-Hexadecimal-to-Decimal ([string]$hexadecimal)
{
$str = '0{0}' -f ($hexadecimal -replace '^0x')
[decimal]([bigint]::Parse($str, [System.Globalization.NumberStyles]::AllowHexSpecifier))
}
function Get-AVAX-Balance ($address)
{
$result = Invoke-RestMethod -Uri 'https://api.avax.network/ext/bc/C/rpc' -Method Post -ContentType 'application/json' -Body (ConvertTo-Json @{
jsonrpc = "2.0"
method = "eth_getBalance"
params = @($address, "latest")
id = 1
})
(Convert-Hexadecimal-to-Decimal $result.result) / [math]::Pow(10,18)
}
PS C:\> Get-AVAX-Balance '0xB9F79Fc4B7A2F5fB33493aB5D018dB811c9c2f02'
37667.049457617898011819
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | dharmatech |