DeveloperBreeze

Ethereum Development Tutorials, Guides & Insights

Unlock 16+ expert-curated ethereum tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your ethereum skills on DeveloperBreeze.

Understanding `crypto.randomBytes` and `ethers.randomBytes`: A Comparison

Tutorial October 24, 2024

  • crypto.randomBytes:
  • Takes a single argument specifying the number of bytes.
  • Always requires a size input; no default value is provided.
  • ethers.randomBytes:
  • Optionally takes the number of bytes to generate.
  • If no argument is provided, it defaults to generating 32 bytes.

Both crypto.randomBytes and ethers.randomBytes generate cryptographically secure random bytes, meaning the bytes are suitable for use in cryptographic applications such as key generation, encryption, and other security-sensitive operations.

How to Query ERC-20 Token Balances and Transactions Using Ethers.js and Etherscan API

Tutorial October 24, 2024

npm install ethers
npm install axios

In this step, we will use Ethers.js to query the balance of an ERC-20 token for a specific Ethereum address.

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

Tutorial October 24, 2024

Use Infura when you need to interact with the Ethereum blockchain in real-time. Infura allows you to send transactions, deploy contracts, and interact with smart contracts. It is essential for decentralized applications (dApps) and any use case where you need to write to the blockchain.

const ethers = require('ethers');

// Replace with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with your wallet's private key
const privateKey = 'YOUR_PRIVATE_KEY';

// Create a wallet instance and connect it to Infura
const wallet = new ethers.Wallet(privateKey, infuraProvider);

// Replace with the recipient's Ethereum address
const recipientAddress = '0xRecipientEthereumAddress';

// Amount to send (in Ether)
const amountInEther = '0.01';

async function sendTransaction() {
  try {
    const tx = {
      to: recipientAddress,
      value: ethers.utils.parseEther(amountInEther),
      gasLimit: 21000, // Gas limit for a basic transaction
      gasPrice: await infuraProvider.getGasPrice() // Get current gas price from Infura
    };

    // Send the transaction
    const transaction = await wallet.sendTransaction(tx);
    console.log('Transaction Hash:', transaction.hash);

    // Wait for the transaction to be mined
    const receipt = await transaction.wait();
    console.log('Transaction Confirmed:', receipt);
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
}

sendTransaction();

Sending Transactions and Interacting with Smart Contracts Using Infura and Ethers.js

Tutorial October 24, 2024

const ethers = require('ethers');

// Replace with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with the ERC-20 contract address (e.g., USDT, DAI, or any token)
const contractAddress = '0xTokenContractAddress';

// Replace with the wallet address to query the balance
const walletAddress = '0xYourWalletAddress';

// ABI of the ERC-20 token (we only need the balanceOf function here)
const abi = [
    'function balanceOf(address owner) view returns (uint256)'
];

// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, infuraProvider);

async function getTokenBalance() {
    try {
        // Call the balanceOf function
        const balance = await contract.balanceOf(walletAddress);

        // Convert the balance from wei (for ERC-20 tokens, it could be small denominations)
        console.log(`Token Balance: ${balance.toString()}`);
    } catch (error) {
        console.error('Error fetching token balance:', error);
    }
}

// Call the function to query the token balance
getTokenBalance();
  • Contract Address: Replace '0xTokenContractAddress' with the ERC-20 token contract’s address (for example, USDT, DAI, etc.).
  • Wallet Address: Replace '0xYourWalletAddress' with the wallet address whose balance you want to query.
  • ABI (Application Binary Interface): The ABI specifies the functions and data structures used in the smart contract. In this case, we’re using a simple balanceOf function to query the balance.

Understanding and Using the Etherscan API to Query Blockchain Data

Tutorial October 24, 2024

You can also query ERC-20 token balances for a given address using the Etherscan API.

const axios = require('axios');

// Replace this with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';

// Replace this with the Ethereum address you want to query
const address = '0xYourEthereumAddress';

// Replace this with the contract address of the ERC-20 token
const contractAddress = '0xYourTokenContractAddress';

// Etherscan API URL to fetch the ERC-20 token balance
const url = `https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=${contractAddress}&address=${address}&tag=latest&apikey=${apiKey}`;

async function getTokenBalance() {
  try {
    // Make the API request to Etherscan
    const response = await axios.get(url);
    const tokenBalance = response.data.result;

    // Log the token balance (Note: Token balances are often in very small denominations)
    console.log(`Token Balance: ${tokenBalance}`);
  } catch (error) {
    console.error('Error fetching token balance:', error);
  }
}

// Call the function to get the token balance
getTokenBalance();