DeveloperBreeze

In this tutorial, we will compare Etherscan and Infura, two popular services for interacting with the Ethereum blockchain. Both provide APIs, but they serve different purposes and are suited for different types of applications. By understanding the strengths of each, you can choose the right one based on your specific use case, whether it involves querying blockchain data or interacting with the Ethereum network in real-time.


Prerequisites

  • Basic understanding of Ethereum and blockchain concepts.
  • Familiarity with APIs and programming in Node.js or any other language.

Step 1: Understanding Etherscan and Infura

Before diving into code examples, it's important to understand the core differences between Etherscan and Infura.

  • Etherscan:
  • Primarily a block explorer and data provider. It offers read-only access to Ethereum blockchain data such as transaction histories, balances, token transfers, and more.
  • Does not allow real-time interaction with the blockchain (e.g., sending transactions).
  • Ideal for querying historical data and performing analytics on blockchain data.
  • Infura:
  • Provides full node access to the Ethereum network, allowing developers to interact with the blockchain in real-time.
  • Supports read and write operations, such as sending transactions, deploying smart contracts, and interacting with dApps.
  • Best for applications that require real-time interaction with Ethereum, such as decentralized apps (dApps).

Step 2: When to Use Etherscan

You should use Etherscan when you need to read data from the Ethereum blockchain, such as querying transaction details, wallet balances, or token transfers. Etherscan is a powerful tool for building blockchain explorers or applications that focus on data analytics.

Example 1: Querying Wallet Balance Using Etherscan API

  1. Create a file etherscanQuery.js to query a wallet balance.
const axios = require('axios');

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

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

// Etherscan API URL to fetch wallet balance
const url = `https://api.etherscan.io/api?module=account&action=balance&address=${address}&tag=latest&apikey=${apiKey}`;

async function getWalletBalance() {
  try {
    const response = await axios.get(url);
    const balanceInWei = response.data.result;

    // Convert balance from Wei to Ether
    const balanceInEther = balanceInWei / 1e18;
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
  } catch (error) {
    console.error('Error fetching balance:', error);
  }
}

getWalletBalance();

Explanation:

  • API: This script sends a GET request to Etherscan's API to fetch the balance of the specified Ethereum wallet.
  • Use Case: Ideal for applications needing read-only access to Ethereum data.

Step 3: When to Use Infura

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.

Example 2: Sending Ether Using Infura and Ethers.js

  1. Create a file infuraTransaction.js to send a transaction.
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();

Explanation:

  • API: This script uses Infura’s node access and Ethers.js to send Ether in real-time.
  • Use Case: Essential for dApps, wallets, or any application needing to send transactions or interact with the blockchain live.

Step 4: Differences in Use Cases

Etherscan Use Cases:

  • Data Analytics: Use Etherscan if you need to fetch historical data, such as transaction histories, token balances, or account balances.
  • Blockchain Explorers: Ideal for building tools similar to Etherscan itself, where you query and display blockchain data to users.
  • Read-Only Data: You can’t send transactions, but you can retrieve information about any Ethereum address, smart contract, or token transfer.

Infura Use Cases:

  • Decentralized Applications (dApps): If you’re building an application that needs to interact with Ethereum in real-time, such as sending transactions or calling smart contract functions.
  • Wallets: If you are developing a wallet application that needs to sign and broadcast transactions.
  • Smart Contract Deployment: Use Infura to deploy or interact with smart contracts on the Ethereum blockchain.

Step 5: Performance and Scalability

Etherscan:

  • Rate Limits: Etherscan’s free tier limits the number of API requests per second (usually around 5 per second). This is fine for querying data but can be limiting for large-scale applications that need to process a lot of data quickly.
  • Pricing: Etherscan offers paid tiers that increase the API request limits.

Infura:

  • Rate Limits: Infura’s free tier provides a generous number of requests (e.g., 100,000 requests per day) and supports more requests as you scale. This makes it more suitable for real-time dApps.
  • Pricing: Infura’s paid plans offer higher limits and additional features like access to Layer 2 networks.

Step 6: Choose Based on Your Use Case

  • Use Etherscan if:
  • You only need to read blockchain data.
  • You want to build tools for analytics or explorers.
  • You don’t need to send transactions or interact directly with smart contracts.
  • Use Infura if:
  • You need to interact with the Ethereum blockchain in real-time.
  • You’re building dApps, wallets, or tools that require transactions.
  • You need to write data to the blockchain, such as sending Ether or deploying contracts.

Step 7: Combining Etherscan and Infura

In some cases, you might want to use both Etherscan and Infura. For example, you might use Etherscan to query transaction histories or token transfers, and Infura to send transactions or deploy contracts.

Example:

  • Etherscan: Use to fetch transaction history and display it in your dApp.
  • Infura: Use to allow users to send transactions or interact with smart contracts.

Conclusion

Etherscan and Infura serve different purposes in the Ethereum ecosystem. Etherscan is perfect for applications that need to query blockchain data, while Infura is essential for real-time interaction with the blockchain. By understanding the strengths of each, you can choose the best service for your project, or even combine them to build powerful Ethereum applications.


Continue Reading

Discover more amazing content handpicked just for you

Tutorial

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

    const crypto = require('crypto');
    const randomBytes = crypto.randomBytes(32);
    console.log(randomBytes.toString('hex')); // Prints a 32-byte random hex string
  • ethers.randomBytes:
  • Library: ethers.randomBytes is provided by the ethers.js library, a popular JavaScript library for Ethereum development. You need to install and include ethers.js as a dependency in your project to use this function.
  • Usage: This function optionally takes the number of bytes you want to generate. If no argument is passed, it defaults to generating 32 bytes. It returns a Uint8Array of random bytes.
  • Example:

Oct 24, 2024
Read More
Tutorial

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

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

const ethers = require('ethers');

// Replace with your Infura or other Ethereum node provider URL
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

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

// Replace with the wallet address you want to query
const walletAddress = '0xYourEthereumAddress';

// ERC-20 token ABI (just the balanceOf function)
const abi = [
    'function balanceOf(address owner) view returns (uint256)'
];

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

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

        // Convert balance to a human-readable format (tokens usually have 18 decimals)
        const formattedBalance = ethers.utils.formatUnits(balance, 18);

        console.log(`Token Balance: ${formattedBalance}`);
    } catch (error) {
        console.error('Error fetching token balance:', error);
    }
}

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

Oct 24, 2024
Read More
Tutorial

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

Once the script is ready, run it using Node.js:

node sendTransaction.js

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

Before you begin, you’ll need the following:

  • Node.js installed on your machine.
  • A basic understanding of JavaScript.
  • An Etherscan API key (explained below).

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Now, let's create a script to query the balance of an Ethereum wallet. This script will work with both Infura and public nodes.

const ethers = require('ethers');

// Replace this with your Ethereum wallet's private key or mnemonic phrase
const privateKey = 'YOUR_PRIVATE_KEY_OR_MNEMONIC';

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

// Create a wallet instance using your private key and connect it to the Infura provider
const wallet = new ethers.Wallet(privateKey, infuraProvider);

// Function to get the balance of the wallet
async function getWalletBalance() {
    // Get the wallet's balance in wei
    const balanceInWei = await wallet.getBalance();

    // Convert the balance from wei to Ether for readability
    const balanceInEther = ethers.utils.formatEther(balanceInWei);

    // Log the results
    console.log(`Wallet Address: ${wallet.address}`);
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
}

// Execute the function
getWalletBalance();

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

  • Overuse: If token burns are overused or if the project relies too heavily on them to drive up value, it can create instability in the market.
  • Misuse: Token burns can be misused by projects to manipulate token value artificially, without creating any real underlying value or utility for the token.
  • Irreversibility: Once tokens are sent to a burn address like "0x000000000000000000000000000000000000dead," they cannot be retrieved, even if the burn was done accidentally.

The "0x000000000000000000000000000000000000dead" address plays a vital role in the cryptocurrency ecosystem, acting as a black hole for tokens that need to be permanently removed from circulation. Token burns, when done responsibly, can reduce supply, increase scarcity, and potentially drive up the value of a cryptocurrency. However, it’s important to understand the potential risks and long-term impacts of token burns before making investment decisions based on burn events.

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

ETH (Ethereum) is the native cryptocurrency of the Ethereum blockchain. It is used for various purposes within the Ethereum ecosystem, including:

  • Transaction Fees: ETH is required to pay gas fees, which are used to process transactions and execute smart contracts on the Ethereum network.
  • Store of Value: ETH, like Bitcoin, is often used as a store of value or an investment asset.
  • Participating in dApps: ETH is essential for interacting with decentralized applications (dApps) that run on the Ethereum network.

Oct 24, 2024
Read More
Tutorial
php

بناء API متقدم باستخدام Laravel Passport للتوثيق

افتح ملف .env وعدل إعدادات قاعدة البيانات لتتناسب مع بيئتك:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=passport_api
DB_USERNAME=root
DB_PASSWORD=

Sep 27, 2024
Read More
Tutorial
rust

Using Solana's Program Library: Building Applications with Pre-Built Functions

Next, we'll add dependencies for the SPL programs we intend to use. For example, if we're working with the SPL Token Program, we'll add the spl-token crate.

Open your Cargo.toml file and add the following dependencies:

Aug 27, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A security analysis service for Ethereum smart contracts.
  • Key Features:
  • Performs deep analysis of smart contracts to identify vulnerabilities.
  • Integrates with popular development tools like Truffle and Hardhat.
  • Provides detailed security reports with identified issues and mitigation suggestions.
  • Supports automated security testing in CI/CD pipelines.
  • Website: MythX
  • Description: A static analysis tool for Solidity smart contracts, focused on security.
  • Key Features:
  • Detects security vulnerabilities and best practice violations.
  • Integrates with CI/CD pipelines for continuous security testing.
  • Provides detailed analysis and recommendations.
  • Compatible with all Solidity versions.
  • Website: Slither

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

     // SPDX-License-Identifier: MIT
     pragma solidity ^0.8.0;

     import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
     import "@openzeppelin/contracts/access/Ownable.sol";

     contract MyToken is ERC20, Ownable {
         constructor(string memory name, string memory symbol, uint256 initialSupply) ERC20(name, symbol) {
             _mint(msg.sender, initialSupply);
         }

         function mint(address to, uint256 amount) public onlyOwner {
             _mint(to, amount);
         }

         function burn(uint256 amount) public {
             _burn(msg.sender, amount);
         }
     }
  • ERC20: Inherits from the OpenZeppelin ERC20 contract, which implements the standard ERC-20 functions and events.
  • Ownable: Provides basic authorization control, allowing the contract owner to perform restricted actions.
  • Constructor: Initializes the token with a name, symbol, and initial supply, which is minted to the contract creator’s address.
  • Mint Function: Allows the contract owner to mint new tokens to a specified address.
  • Burn Function: Allows token holders to destroy (burn) their tokens, reducing the total supply.

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Function Modifiers:

- view: Indicates that the function does not modify the state.

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

1. Uniswap

  • Optimization: Uniswap V2 introduced several optimizations, including reducing the number of state changes in core functions and using assembly code for certain operations.
  • Impact: These optimizations led to significant gas savings, making Uniswap more cost-effective for users.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Example Front-End Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Message DApp</title>
</head>
<body>
    <h1>Decentralized Message Store</h1>
    <input type="text" id="messageInput" placeholder="Enter a new message">
    <button onclick="setMessage()">Set Message</button>
    <p id="currentMessage">Loading message...</p>

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script>
        const contractAddress = 'YOUR_CONTRACT_ADDRESS';
        const abi = [/* ABI from compiled contract */];

        const web3 = new Web3(Web3.givenProvider);
        const contract = new web3.eth.Contract(abi, contractAddress);

        async function setMessage() {
            const accounts = await web3.eth.getAccounts();
            const message = document.getElementById('messageInput').value;
            await contract.methods.setMessage(message).send({ from: accounts[0] });
            loadMessage();
        }

        async function loadMessage() {
            const message = await contract.methods.getMessage().call();
            document.getElementById('currentMessage').innerText = message;
        }

        window.onload = loadMessage;
    </script>
</body>
</html>

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

  • Decentralized: Operates on the blockchain, not controlled by any single entity.
  • Trustless: Executes automatically when conditions are met, without requiring trust between parties.
  • Immutable: Once deployed, the contract's code cannot be changed, ensuring the terms are fixed.

Before writing a smart contract, we need to set up a development environment. Here’s what you need:

Aug 22, 2024
Read More
Tutorial
javascript solidity

Creating a Decentralized Application (dApp) with Solidity, Ethereum, and IPFS: From Smart Contracts to Front-End

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyDapp {
    string public ipfsHash;

    event IPFSHashChanged(string newIPFSHash);

    function setIPFSHash(string memory newIPFSHash) public {
        ipfsHash = newIPFSHash;
        emit IPFSHashChanged(newIPFSHash);
    }

    function getIPFSHash() public view returns (string memory) {
        return ipfsHash;
    }
}

Update the React component to include IPFS integration:

Aug 20, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

Replace the placeholders with your actual database details.

Migrations in Laravel allow you to define and modify your database schema. Let's create a migration for a posts table:

Aug 14, 2024
Read More
Tutorial
python

Advanced Pybit Tutorial: Managing Leverage, Stop-Loss Orders, Webhooks, and More

This Flask app listens for POST requests on /webhook and prints the received data. You can expand this to handle specific webhook events like order fills, price alerts, etc.

Managing open orders and closing positions is essential for effective trading. Pybit makes it straightforward to close orders.

Aug 14, 2024
Read More
Tutorial
python

A Beginner's Guide to Pybit: Interacting with the Bybit API

   def place_limit_order(symbol, side, qty, price):
       response = session.place_active_order(
           symbol=symbol,
           side=side,
           order_type='Limit',
           qty=qty,
           price=price,
           time_in_force='GoodTillCancel'
       )
       if response['ret_code'] != 0:
           print(f"Error placing order: {response['ret_msg']}")
       return response

This tutorial provided a basic introduction to using Pybit to interact with the Bybit API. You've learned how to set up the Pybit client, fetch market data, place orders, and handle errors. With these basics, you can start building more complex trading bots and analytics tools on top of Bybit.

Aug 14, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

In this tutorial, we will learn how to track newly created tokens on the Ethereum blockchain. With the rapid growth of decentralized finance (DeFi) and non-fungible tokens (NFTs), keeping an eye on newly created tokens can be valuable for investors, developers, and enthusiasts. We will use Etherscan's API to monitor token creation events and Web3.js to interact with the Ethereum network.

Prerequisites

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!