Interacting with Smart Contracts via Web3.js

๐Ÿ”น What is Web3.js?


Web3.js is a JavaScript library that allows developers to interact with the Ethereum blockchain. It provides APIs to:


Connect to Ethereum nodes


Read and write blockchain data


Interact with deployed smart contracts


๐Ÿ”น Steps to Interact with Smart Contracts via Web3.js

1. Install Web3.js

npm install web3


2. Connect to an Ethereum Node


You can use providers like Infura, Alchemy, or Ganache.


const Web3 = require("web3");


// Example with Infura

const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");


3. Get the Smart Contract ABI and Address


ABI (Application Binary Interface): Defines how to interact with the contract (functions, events).


Contract Address: The location of the deployed contract on the blockchain.


Example:


const contractABI = [/* ABI JSON here */];

const contractAddress = "0x123456789abcdef...";


4. Create a Contract Instance

const myContract = new web3.eth.Contract(contractABI, contractAddress);


5. Call Read-Only Functions (no gas required)


For example, getting a token balance:


async function getBalance(address) {

  const balance = await myContract.methods.balanceOf(address).call();

  console.log("Balance:", balance);

}


6. Send Transactions (state-changing functions, gas required)


To interact with functions that modify the blockchain (e.g., transfer tokens), you need a wallet with private keys.


const account = "0xYourEthereumAddress";

const privateKey = "0xYourPrivateKey";


async function transferTokens(to, amount) {

  const tx = {

    to: contractAddress,

    data: myContract.methods.transfer(to, amount).encodeABI(),

    gas: 200000,

  };


  const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);

  const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

  console.log("Transaction receipt:", receipt);

}


7. Listen to Smart Contract Events


Smart contracts emit events you can subscribe to:


myContract.events.Transfer({

  fromBlock: "latest"

})

.on("data", (event) => {

  console.log("Transfer Event:", event.returnValues);

});


๐Ÿ”น Summary


Use Web3.js to connect to Ethereum.


Get the ABI and contract address.


Use .call() for read-only functions.


Use .send() with a signed transaction for write functions.


Listen for events to track smart contract activity.

Learn Blockchain Course in Hyderabad

Read More

Writing Upgradable Smart Contracts

Building an NFT Marketplace from Scratch

Flash Loan Arbitrage: Real-World Examples

Flash Loan Arbitrage: Real-World Examples


Comments

Popular posts from this blog

Handling Frames and Iframes Using Playwright

Cybersecurity Internship Opportunities in Hyderabad for Freshers

Tosca for API Testing: A Step-by-Step Tutorial