What is an Ethereum Address?
An Ethereum address is a unique identifier that represents an account on the Ethereum blockchain. Each address can hold Ether (ETH) and other tokens, and it is essential to check the balance of an address to understand its current holdings.
Purpose of Checking an Address Balance
Checking the balance of an Ethereum address is crucial for various reasons, including:
- Determining the available funds for transactions.
- Monitoring the balance for investment purposes.
- Verifying the receipt of funds after a transaction.
Using Ethers.js to Check an Address Balance
Ethers.js provides a simple method to check the balance of an address using the provider.getBalance(address)
function. This function returns the balance in Wei, which can be converted to Ether for easier readability.
Syntax
const balance = await provider.getBalance(address);
- address
: The Ethereum address for which you want to check the balance.
Sample Code for Checking an Address Balance
Below is an example demonstrating how to check the balance of an Ethereum address using Ethers.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ethers.js Check Balance Example</title>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.0/dist/ethers.umd.min.js"></script>
</head>
<body>
<h1>Check Ethereum Address Balance</h1>
<input type="text" id="addressInput" placeholder="Enter Ethereum Address" />
<button id="checkBalanceButton">Check Balance</button>
<pre id="balanceOutput"></pre>
<script>
// Connect to the Ethereum network (default to mainnet)
const provider = new ethers.providers.getDefaultProvider();
document.getElementById('checkBalanceButton').onclick = async function() {
const address = document.getElementById('addressInput').value;
try {
const balance = await provider.getBalance(address);
// Convert balance from Wei to Ether
const balanceInEther = ethers.utils.formatEther(balance);
document.getElementById('balanceOutput').innerText =
"Balance: " + balanceInEther + " ETH";
} catch (error) {
document.getElementById('balanceOutput').innerText =
"Error: " + error.message;
}
};
</script>
</body>
</html>
Conclusion
Checking the balance of an Ethereum address using Ethers.js is straightforward with the provider.getBalance()
method. By using this method, developers can easily retrieve and display the balance of any Ethereum address, facilitating better interaction with the Ethereum blockchain.