Published on October 24, 2024By DeveloperBreeze

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

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](https://infura.io/).
  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.

Comments

Please log in to leave a comment.

Continue Reading:

Weather App with Node.js

Published on August 08, 2024

javascript

Building a Simple Solana Smart Contract with Anchor

Published on August 09, 2024

javascriptbashrustnodejs

Fetching Address Details from Solana

Published on August 09, 2024

javascriptjson

Tracking Newly Created Tokens on Ethereum

Published on August 09, 2024

javascriptnodejs

Tracking Newly Created Tokens on Solana

Published on August 09, 2024

javascriptnodejs

Tracking Solana Address for New Trades and Amounts

Published on August 09, 2024

javascriptnodejs

Node.js: How to Create an HTTP Server

Published on August 12, 2024

javascriptnodejs

GraphQL API Server with Node.js and Apollo Server

Published on August 12, 2024

nodejsgraphql

Building a GraphQL API with Node.js and Apollo Server

Published on August 12, 2024

javascriptnodejsgraphql