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
How to Use the ‘5 Whys’ to Clarify Your Career Goals
Titan: Members-Only Wealth Platform
Diario Las Americas Rentas Hialeah
Best Pizza Novato
Rubratings Tampa
UPS Paketshop: Filialen & Standorte
Tv Guide Bay Area No Cable
Corpse Bride Soap2Day
Seth Juszkiewicz Obituary
Items/Tm/Hm cheats for Pokemon FireRed on GBA
Syracuse Jr High Home Page
Busty Bruce Lee
Calmspirits Clapper
Used Drum Kits Ebay
Grasons Estate Sales Tucson
Wizard Build Season 28
Nutrislice Menus
Transfer and Pay with Wells Fargo Online®
Virginia New Year's Millionaire Raffle 2022
A Man Called Otto Showtimes Near Cinemark University Mall
F45 Training O'fallon Il Photos
Tuw Academic Calendar
Relaxed Sneak Animations
Cylinder Head Bolt Torque Values
Mjc Financial Aid Phone Number
Viduthalai Movie Download
Sinfuldeed Leaked
Parent Management Training (PMT) Worksheet | HappierTHERAPY
Ghid depunere declarație unică
Advance Auto Parts Stock Price | AAP Stock Quote, News, and History | Markets Insider
October 19 Sunset
Smayperu
Iban's staff
Closest 24 Hour Walmart
Imperialism Flocabulary Quiz Answers
Sinai Sdn 2023
The Bold And The Beautiful Recaps Soap Central
Ishow Speed Dick Leak
When His Eyes Opened Chapter 2048
“Los nuevos desafíos socioculturales” Identidad, Educación, Mujeres Científicas, Política y Sustentabilidad
Bcy Testing Solution Columbia Sc
Vindy.com Obituaries
boston furniture "patio" - craigslist
Pathfinder Wrath Of The Righteous Tiefling Traitor
Neil Young - Sugar Mountain (2008) - MusicMeter.nl
Enjoy Piggie Pie Crossword Clue
Game Akin To Bingo Nyt
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Tweedehands camper te koop - camper occasion kopen
Convert Celsius to Kelvin
Basic requirements | UC Admissions
Saw X (2023) | Film, Trailer, Kritik
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.