DeveloperBreeze

In this tutorial, we will walk through how to use Ethers.js along with Infura to send Ethereum transactions and interact with smart contracts. Infura provides scalable access to Ethereum nodes, allowing you to interact with the blockchain in real-time without running your own node.

By the end of this tutorial, you will be able to send Ether, call smart contract functions, and deploy contracts using Infura as your provider.


Prerequisites

To follow along with this tutorial, you’ll need:

  • Node.js installed on your machine.
  • A basic understanding of JavaScript and blockchain concepts.
  • An Ethereum wallet with some test ETH (using testnets like Goerli or Ropsten is recommended for testing).
  • An Infura Project ID to access the Ethereum network.

Step 1: Set Up Infura and Obtain an API Key

If you don't have an Infura account yet, follow these steps:

  1. Go to Infura’s website.
  2. Sign up for an account.
  3. Create a new project and select Ethereum as the network.
  4. Copy the Project ID and Project Secret from the settings — this will be used as your API key.

Step 2: Install Ethers.js

You’ll use Ethers.js to interact with Ethereum smart contracts and send transactions. Run the following command in your project folder to install it:

npm install ethers

Step 3: Create a Node.js Script for Sending Transactions

Let’s start by sending Ether from one account to another using Ethers.js and Infura.

  1. Create a file called sendTransaction.js.
  2. Add the following code 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 {
        // Convert Ether to Wei (the smallest unit of Ether)
        const amountInWei = ethers.utils.parseEther(amountInEther);

        // Create the transaction
        const tx = {
            to: recipientAddress,
            value: amountInWei,
            gasLimit: ethers.utils.hexlify(21000), // Gas limit for basic transactions
            gasPrice: await infuraProvider.getGasPrice() // Get current gas price from Infura
        };

        // Send the transaction
        const transaction = await wallet.sendTransaction(tx);

        console.log('Transaction sent:', 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);
    }
}

// Call the function to send the transaction
sendTransaction();

Explanation:

  • Infura Provider: You connect to the Ethereum network using the Infura provider (infuraProvider), which allows you to interact with Ethereum nodes.
  • Private Key: Replace 'YOUR_PRIVATE_KEY' with your Ethereum wallet’s private key (keep it secure).
  • Recipient Address: Replace '0xRecipientEthereumAddress' with the Ethereum address you want to send Ether to.
  • Gas and Fees: The gasLimit and gasPrice fields are required for sending transactions. The getGasPrice function retrieves the current gas price from the Infura node.

Step 4: Run the Script to Send Ether

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

node sendTransaction.js

If everything is set up correctly, the script will output the transaction hash after sending, and then confirm once the transaction is mined.

Example output:

Transaction sent: 0xTransactionHash
Transaction confirmed: { transaction details }

Step 5: Interact with a Smart Contract Using Ethers.js

Next, let’s interact with a smart contract using Ethers.js and Infura. For this example, we will call a read-only function from an ERC-20 token contract (like querying the balance of a wallet).

  1. Create a file called contractInteraction.js.
  2. Add the following code:
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();

Explanation:

  • 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.

Step 6: Run the Script to Query Token Balance

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

node contractInteraction.js

If everything is set up correctly, the script will output the token balance of the specified wallet.

Example output:

Token Balance: 1000000000000000000

This output is the token balance in the smallest unit (e.g., Wei for Ether or the smallest denomination for the token), and you can convert it to the token’s base unit if needed.


Step 7: Deploy a Smart Contract (Optional)

Deploying smart contracts is a more advanced topic, but here’s an example of how you can use Ethers.js with Infura to deploy a smart contract:

  1. Create a file called deployContract.js.
  2. Use the following code:
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 private key
const privateKey = 'YOUR_PRIVATE_KEY';

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

// Contract bytecode and ABI
const bytecode = '0xYourContractBytecode';
const abi = [
    // Your contract ABI here
];

async function deployContract() {
    try {
        // Create a ContractFactory to deploy the contract
        const factory = new ethers.ContractFactory(abi, bytecode, wallet);

        // Deploy the contract
        const contract = await factory.deploy();

        // Wait for the contract to be mined
        console.log('Contract deployed at address:', contract.address);
        await contract.deployTransaction.wait();
    } catch (error) {
        console.error('Error deploying contract:', error);
    }
}

// Call the function to deploy the contract
deployContract();

Explanation:

  • Bytecode and ABI: The contract bytecode is the compiled contract, and the ABI defines the contract’s interface. You need both to deploy the contract.
  • The contract will be deployed using your Infura provider and wallet, and once mined, it will return the deployed contract address.

Conclusion

In this tutorial, you learned how to use Ethers.js with Infura to send Ether, interact with smart contracts, and deploy contracts on the Ethereum blockchain. This setup allows you to interact with the blockchain in real-time without the need to run your own Ethereum node, making it easier to develop decentralized applications (dApps) and other blockchain-based services.

Using Infura for node access and Ethers.js for transaction management and contract interaction gives you a powerful combination to build on Ethereum.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

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

  • crypto.randomBytes is part of Node.js, so it requires no external dependencies. This makes it ideal for Node.js environments where minimal dependencies are desired.
  • ethers.randomBytes requires the installation of the ethers.js library, which is primarily designed for blockchain-related projects. This is useful if you're already working with Ethereum, but it adds an external dependency to the project.
  • 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.

Oct 24, 2024
Read More
Tutorial

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

const axios = require('axios');

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

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

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

// Etherscan API URL to fetch ERC-20 token transactions
const url = `https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=${contractAddress}&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=${apiKey}`;

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

        // Log the token transactions
        transactions.forEach(tx => {
            console.log(`
                From: ${tx.from}
                To: ${tx.to}
                Value: ${ethers.utils.formatUnits(tx.value, 18)} Tokens
                Transaction Hash: ${tx.hash}
            `);
        });
    } catch (error) {
        console.error('Error fetching token transactions:', error);
    }
}

// Call the function to get the token transactions
getTokenTransactions();
  • API Key: Replace 'YOUR_ETHERSCAN_API_KEY' with the API key you generated from Etherscan.
  • Wallet Address: Replace '0xYourEthereumAddress' with the wallet address you want to query for token transactions.
  • Token Contract Address: Replace '0xTokenContractAddress' with the contract address of the ERC-20 token you want to track.

Oct 24, 2024
Read More
Tutorial

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

  • 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.

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.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

Let’s extend the functionality by querying transaction details for a specific transaction 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 transaction hash you want to query
const transactionHash = '0xYourTransactionHash';

// Etherscan API URL to fetch transaction details
const url = `https://api.etherscan.io/api?module=proxy&action=eth_getTransactionByHash&txhash=${transactionHash}&apikey=${apiKey}`;

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

    // Log the transaction details
    console.log('Transaction Details:', transactionDetails);
  } catch (error) {
    console.error('Error fetching transaction details:', error);
  }
}

// Call the function to get the transaction details
getTransactionDetails();

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

If you don't want to use Infura, you can connect to a public Ethereum node:

const ethers = require('ethers');

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

// Use a public Ethereum node URL (this is a public node for demonstration purposes)
const publicProvider = new ethers.JsonRpcProvider('https://mainnet.publicnode.com');

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

// 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

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

WETH essentially bridges the gap between ETH and the broader ERC-20 ecosystem, allowing ETH to function seamlessly in DeFi, token swaps, and other smart contract interactions.

Wrapping ETH into WETH is a simple process that can be done through various decentralized exchanges or applications. Here’s a typical process:

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  • Description: A decentralized computing network and app ecosystem designed to build decentralized applications on top of blockchains.
  • Use Cases:
  • Build decentralized applications with identity, storage, and smart contracts.
  • Use Gaia storage for decentralized file storage.
  • Implement user authentication and identity management in DApps.
  • Key Features:
  • Provides SDKs for JavaScript, iOS, and Android.
  • Integrates easily with existing blockchains and decentralized storage solutions.
  • Focused on privacy and user data ownership.
  • Installation:

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: The official documentation for OpenZeppelin’s smart contract libraries and tools.
  • Key Features:
  • Guides on using OpenZeppelin Contracts, SDK, and Defender.
  • Best practices for secure smart contract development.
  • Tutorials on integrating OpenZeppelin tools with DApps.
  • Regularly updated with the latest security features.
  • Website: OpenZeppelin Documentation
  • Description: An interactive tutorial platform for learning Solidity by building a game.
  • Key Features:
  • Step-by-step lessons on Solidity and smart contract development.
  • Interactive coding exercises and challenges.
  • Gamified learning experience.
  • Covers basic to advanced Solidity topics.
  • Website: CryptoZombies

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

     touch scripts/deploy.js
  • Open deploy.js and add the following code:

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

Mappings are key-value stores, often used to associate addresses with balances.

mapping(address => uint) public balances;

function updateBalance(address _address, uint _amount) public {
    balances[_address] = _amount;
}

function getBalance(address _address) public view returns (uint) {
    return balances[_address];
}

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

Understanding gas and optimizing its consumption in smart contracts is crucial for developing cost-effective and efficient decentralized applications. By implementing strategies such as minimizing storage writes, using view and pure functions, optimizing loops, and leveraging efficient data structures, you can significantly reduce the gas costs associated with your smart contracts.

As you continue your journey in Ethereum development, keep refining your skills in gas optimization and stay updated with best practices and tools. Gas efficiency not only saves costs but also contributes to the overall scalability and usability of the Ethereum network.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Key Characteristics of DApps:

  • Decentralized: Operates on a blockchain network.
  • Open-source: The code is public and available for anyone to view and audit.
  • Autonomous: Once deployed, it runs independently without human intervention.
  • Smart Contract Integration: Relies on smart contracts to execute transactions and operations.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

  • Set a Value: Use the set function to store a number in the contract.
  • Get the Value: Use the get function to retrieve the stored number.

You’ll notice that calling the set function will require gas (a small amount of Ether) to execute, whereas calling the get function is free as it’s a view function.

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

Create a new migration file in the migrations directory:

const MyDapp = artifacts.require("MyDapp");

module.exports = function (deployer) {
  deployer.deploy(MyDapp, "Hello, world!");
};

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

  • Etherscan API: We use the tokentx action from Etherscan's API to fetch token transfer events. The API returns a list of token transactions, including newly created tokens.
  • Filter for New Tokens: We filter transactions where the from address is 0x0000000000000000000000000000000000000000, indicating a token creation event. This address is used as a placeholder for the "zero address" in token contracts.
  • Display Information: We log the name, symbol, and contract address of each newly created token.

Step 4: Monitor for New Tokens

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!