How to Calling Smart Contract Functions with Web3.js? - GeeksforGeeks (2024)

Last Updated : 12 Oct, 2023

Summarize

Comments

Improve

Have you wondered how smart contracts interact with the front end? So, the answer is the web3.js library. First, briefly discuss some terms related to web3.js and learn about them.

Web3.js:

Web3. js is a collection of libraries that allow users to interact between smart contracts and the front end. It is used to develop websites that can interact with different blockchains.

Ethereum-based applications can interact with developers through a set of APIs provided by Web3.js. These APIs include:

  • Web3: It is the main interface for interacting with Ethereum Blockchain. It provides functions for interacting with contracts, accounts, and the Ethereum main network or test network.
  • Eth: It is an interface for interacting with the Ethereum network. It provides functions for querying the network and sending transactions.
  • Contract: It provides an interface for interacting with smart contracts. It provides the functionality for interacting, deploying, and listening to events from deployed smart contracts.

Smart Contract:

It is a self-executing program that runs on Ethereum Blockchain and automates the actions required in an agreement or contract. All the transactions done through smart contracts are irreversible and can be traced. Any transaction that modifies blockchain costs gas.

How to Calling Smart Contract Functions with Web3.js? - GeeksforGeeks (1)

Example of Smart Contract

for more detail about Smart Contracts refer to: Smart Contract

functions :

A function in Solidity is a piece of reusable code that can be called within or outside of a smart contract. There is a keyword ‘function’ to define the function in solidity language, which is followed by the function’s name and it is to be noticed that function’s name can’t be any reserved keywords. Function can contains parameter or list of parameters denoting the datatype and name of parameter. It’s optional to return or to not return any value from function but it is defined at the time of declaration.

function function_name(parameter_list) scope returns(return_type) {
// block of code
}

for more about functions in Solidity read the article: Solidity – Functions

Prerequisites :

  • how to write smart contracts in Solidity Language
  • contract deployment on the Testnet or Mainnet of Ethereum using Remix IDE

learn here how to deploy a smart contract: Deploy Contract

Approach :

Main Logic to call the function through web3.js is :

1. Install Web3.js – It is a JavaScript library that helps to interact with Ethereum-based applications. One can install it, using a package manager like yarn or npm. For example, using npm , run the following command in your terminal:

 npm install web3
or
yarn add web3

2. Connection to a Provider – It is an object that allows us to communicate with nodes on Ethereum Blockchain. You can use the default provider provided by MetaMask or make it on your own like Infura. Here, we will use Metamask provider .

Here’s a command how to create a Web3 object and connect to the Metamask provider:

import Web3 from 'web3';
const web3 = new Web3(window.ethereum);

3. Contract ABI loaded from Remix – The ABI (Application Binary Interface) is a file that describes the interface for the smart contract, including the functions that it has Copy the ABI code from Remix IDE and paste it in file named as ‘ABI.json’. One can load the ABI by fetching it from a URL or using the require function in Node.js. In this example, we’ll load it using require:

 import ABI from './ABI.json'
or
const ABI = require('./ABI.json');

4. Instance creation of the Contract – Web3 object is once instantiated and the contract ABI, then one can create an instance of the contract using by calling the web3.eth.Contract() function:

const contract = new web3.eth.Contract( 
ABI,
"Paste the hash or address of smart contract here(example: 0x123456789abcdef123456789abcdef123456789')"
);

Note: Hash or address of smart contract is produced while deploying it on any blockchain. Copy that hash and paste it above.

for testing purpose, deploy the smart contract on test network first and check its accuracy and correctness and then after deploying it on main network.

5. Calling the Contract Functions

Now, we can call any specific function of smart contract using contract.methods object.

Syntax :

contract.methods.<function_name>.call()

Conclusion:

It is very simple to call a contract function using Web3.js. You just need to load the contract ABI, then creation of an instance of the contract, and calling the specific function using the contract.methods object on the contract. With Web3.js, you can interact with Ethereum-based applications from your JavaScript applications, which helps to develop decentralised applications.



A

abhinavtyagi326

How to Calling Smart Contract Functions with Web3.js? - GeeksforGeeks (2)

Improve

Next Article

How to Send ERC20 Token with Web3.js?

Please Login to comment...

How to Calling Smart Contract Functions with Web3.js? - GeeksforGeeks (2024)
Top Articles
Sync your account settings - Chromebook Help
The Goldman Sachs Group, Inc.- Risk Factors
The Daily News Leader from Staunton, Virginia
Health Benefits of Guava
Robinhood Turbotax Discount 2023
Shorthand: The Write Way to Speed Up Communication
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Volstate Portal
Fire Rescue 1 Login
Jasmine Put A Ring On It Age
Guilford County | NCpedia
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Amc Flight Schedule
Michigan cannot fire coach Sherrone Moore for cause for known NCAA violations in sign-stealing case
Equipamentos Hospitalares Diversos (Lote 98)
Craigslist Southern Oregon Coast
Menus - Sea Level Oyster Bar - NBPT
Www.dunkinbaskinrunsonyou.con
Uncovering The Mystery Behind Crazyjamjam Fanfix Leaked
The Many Faces of the Craigslist Killer
Hdmovie2 Sbs
Horn Rank
Used Patio Furniture - Craigslist
Mdt Bus Tracker 27
A Christmas Horse - Alison Senxation
JVID Rina sauce set1
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Jackass Golf Cart Gif
Things to do in Pearl City: Honolulu, HI Travel Guide by 10Best
Astro Seek Asteroid Chart
Ezstub Cross Country
Autotrader Bmw X5
Baldur's Gate 3 Dislocated Shoulder
Sports Clips Flowood Ms
2024 Coachella Predictions
Bt33Nhn
2015 Chevrolet Silverado 1500 for sale - Houston, TX - craigslist
Blackwolf Run Pro Shop
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Letter of Credit: What It Is, Examples, and How One Is Used
Barstool Sports Gif
All-New Webkinz FAQ | WKN: Webkinz Newz
Sand Castle Parents Guide
Trivago Anaheim California
Dragon Ball Super Super Hero 123Movies
Tommy Bahama Restaurant Bar & Store The Woodlands Menu
Backpage New York | massage in New York, New York
The Machine 2023 Showtimes Near Roxy Lebanon
Sam's Club Gas Price Sioux City
Maurices Thanks Crossword Clue
Home | General Store and Gas Station | Cressman's General Store | California
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 5851

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.