Getting Started with ethers: Sending Transactions and Deploying Smart Contracts

Ethers.js is a powerful and lightweight JavaScript library for interacting with Ethereum-compatible blockchains. In this guide, we’ll walk you through setting up your environment, sending transactions, and deploying smart contracts step by step. To get started quickly, we’ll use a pre-configured GitHub repository.

Youttube: https://youtu.be/7F2QELvhxLY?si=YE00Y3ai-TyK5fTt

Step 1: Clone the GitHub Repository

To save time, clone the pre-configured repository with all the essential files:

git clone https://github.com/Vikash-8090-Yadav/Conflux-Tutorial

Step 2: Install Dependenciesz

Run the following command to install the required libraries:

npm install
npm run dev

Step3: Setup the HTTP connection

Prepare your Web3 HTTP connection to align with any evm-powered network. To synchronize your project, you must secure an endpoint and API key of your own.

Here’s how you can get started:

// Create a Web3 instance:


const provider = new  ethers.providers.JsonRpcProvider("https://evmtestnet.confluxrpc.com");

Step 4: Check Account Balances

To check balances, use the balances.js script. Open the file and configure your sender and recipient addresses:


onst balance = await provider.getBalance(address)
      const finalBalance = ethers.utils.formatEther(balance)
      setBalance(finalBalance)

Step 5: Send a Transaction

To send a transaction, use the transaction.js script. Open the file and update it with your private key and addresses:


if (!address) {
      alert('Please connect your wallet first')
      return
    }

    const receiverAddress = '0x80F9839DDfa157498eB112c2081E339FB75bCD35'
    const amountInCFX = '1'

    setSendLoading(true)
    setTransactionHash('')

    try {
      const provider = new ethers.providers.Web3Provider(window.ethereum)
      const signer = await provider.getSigner()
      
      const tx = await signer.sendTransaction({
        to: receiverAddress,
        value: ethers.utils.parseEther(amountInCFX)
      })

      await tx.wait()
      setTransactionHash(tx.hash)
    } catch (error) {
      console.error('Transaction error:', error)
      alert(`Failed to send CFX: ${error.message}`)
    } finally {
      setSendLoading(false)
    }
 

This will transfer 1 ETH from the sender to the receiver and output the transaction hash.

Step 6: Deploy a Smart Contract

Write the Contract
The repository already includes a file named Incrementer.sol. Here’s the content:

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

contract Greeting {
    string private greeting ="Good Luck";

    // Constructor to initialize the greeting
    

    // Function to set a new greeting
    function setGreeting(string memory _newGreeting) public {
        greeting = _newGreeting;
    }

    // Function to get the current greeting
    function getGreeting() public view returns (string memory) {
        return greeting;
    }
}

Deploy the Contract
To deploy the contract, use the deploy.js script. Update it with your private key:


require ('@nomiclabs/hardhat-waffle');
require('@openzeppelin/hardhat-upgrades');
require('@nomicfoundation/hardhat-ethers');
require('@nomicfoundation/hardhat-verify');
module.exports = {
  solidity: "0.8.10",

  defaultNetwork: "confluxTestnet",
  networks:{
    hardhat:{},
    confluxTestnet: {
      url: "https://evmtestnet.confluxrpc.com	" || "",
      chainId:71 ,
      accounts: ['prvtekey']
    },
  }
};

Step 7: Interact with the Contract

Read Contract Data

Use the get.js script to fetch the current value:

 try {
      const contract = new ethers.Contract(smartcontractAddress, ABI.abi, provider);
      const result = await contract.getGreeting();
      setReadResult(result);
    } catch (error) {
      console.error('Error reading from smart contract:', error);
      alert('Failed to read from smart contract. Please try again.');
    }

Write Contract Data
Use the increment.js script to increment the value:


 if (!address) {
      alert('Please connect your wallet first')
      return
    }
    
    if (!newGreeting) {
      alert('Please enter a new greeting')
      return
    }

    setWriteLoading(true)
    setWriteTransactionHash('')
    
    try {
      const provider = new ethers.providers.Web3Provider(window.ethereum)
      const signer = await provider.getSigner()
      const contract = new ethers.Contract(smartcontractAddress, ABI.abi, signer)
      
      const tx = await contract.setGreeting(newGreeting)
      await tx.wait()
      setWriteTransactionHash(tx.hash)
      setNewGreeting('')
    } catch (error) {
      console.error('Error writing to smart contract:', error)
      alert(`Failed to update greeting: ${error.message}`)
    } finally {
      setWriteLoading(false)
    }

Conclusion
Congratulations! You’ve successfully set up as ethers project, sent transactions, deployed a smart contract, and interacted with it. This workflow lays the foundation for building robust blockchain applications.

Feel free to explore further by modifying the Incrementer.sol contract or integrating other ethers features. Happy coding! :rocket: