Skip to content

Instantly share code, notes, and snippets.

@Krishprajapati15
Created May 5, 2025 15:53
Show Gist options
  • Select an option

  • Save Krishprajapati15/5da8c5b433bbaf0cfc55a744077f1b80 to your computer and use it in GitHub Desktop.

Select an option

Save Krishprajapati15/5da8c5b433bbaf0cfc55a744077f1b80 to your computer and use it in GitHub Desktop.
This Gist demonstrates how to interact with the Ethereum blockchain using the Web3.js library. It includes simple, beginner-friendly examples such as connecting to the Ethereum mainnet using Infura, retrieving the latest block number, and checking the ETH balance of any Ethereum address. This code is ideal for developers who are starting with We…

πŸ”— Web3.js Ethereum Interaction Gist

This Gist demonstrates basic interactions with the Ethereum blockchain using the Web3.js library. You can:

  • Connect to the Ethereum mainnet via Infura.
  • Fetch the latest block number.
  • Check the ETH balance of any Ethereum address.

πŸ›  Requirements

  • Node.js installed
  • Web3.js installed (npm install web3)
  • A valid Infura project URL

πŸ’‘ Note

Replace 'YOUR_INFURA_PROJECT_ID' with your actual Infura project ID.

// web3js-eth-interaction.js
// Import Web3
const Web3 = require('web3');
// Connect to the Ethereum blockchain using Infura (or local node)
const INFURA_URL = 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';
const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_URL));
// Example: Get the latest block number
async function getLatestBlock() {
const blockNumber = await web3.eth.getBlockNumber();
console.log('Latest Block Number:', blockNumber);
}
// Example: Get ETH balance of an address
async function getBalance(address) {
const balanceWei = await web3.eth.getBalance(address);
const balanceEth = web3.utils.fromWei(balanceWei, 'ether');
console.log(`Balance of ${address}: ${balanceEth} ETH`);
}
// Example usage
(async () => {
await getLatestBlock();
await getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e'); // Sample address
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment