How to interact with smart contracts using JavaScript

Smart contracts are the main building blocks for Web3 applications. To enable functions in a Web3 application, it is important that you can conveniently interact with the functions specified in the smart contract. You can use a popular language like JavaScript and the well-known Web3.js library to establish this communication.

How to interact with smart contracts using JavaScript Picture 1

What is Web3.js library?

Web3.js is a JavaScript library that provides an interface to the Ethereum blockchain. It simplifies the process of building decentralized applications (DApps) by providing methods and tools to connect to Ethereum nodes, send transactions, read smart contract data, and process events. to sue.

Web3.js connects blockchain technology with traditional development, allowing you to create secure and decentralized applications using familiar JavaScript syntax and functions.

How to import Web3.js into a JavaScript project

To use Web3.js in a Node project, you first need to install the library as a dependency of the project.

Install the library by running the following command inside the project:

 

npm install web3 hoặc yarn add web3

After installing Web3.js , you can now import the library in your Node project as an ES module:

const Web3 = require('web3');

Interaction with deployed smart contract

To illustrate how you can interact with smart contracts deployed on the Ethereum network using Web3.js, you will create a web application that works with the deployed smart contract. The purpose of the web application will be a simple voting ballot where the wallet can vote for a candidate and record those votes.

To get started, create a new directory for your project and initialize it as a Node.js project:

npm init

Install Web3.js as a dependency and create a simple index.html and styles.css file in the project root directory.

Enter the following code in the index.html file :

 Voting App 

Voting App

 Candidate A Vote 0 votes Candidate B Vote 0 votes Candidate C Vote 0 votes 

Inside the styles.css file , enter the following code:

/* styles.css */ body { font-family: Arial, sans-serif; text-align: center; } h1 { margin-top: 30px; } .candidates { display: flex; justify-content: center; margin-top: 50px; } .candidate { margin: 20px; } .name { font-weight: bold; } .vote-btn { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } .vote-count { margin-top: 5px; }

 

Below is the resulting interface:

How to interact with smart contracts using JavaScript Picture 2

Now that you have a basic interface to start with, create a contract folder in the root of your project that contains the code for the smart contract.

Remix IDE provides a simple way to write, deploy, and test smart contracts . You will use Remix to deploy contracts to the Ethereum network.

Navigate to remix.ethereum.org and create a new file in the contracts folder . You can name the file test_contract.sol .

How to interact with smart contracts using JavaScript Picture 3

The .sol extension says this is a Solidity file - one of the most popular languages ​​for writing modern smart contracts.

Inside this file, write and compile the Solidity code:

// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Voting { mapping(string => uint256) private voteCounts; function vote(string memory candidate) public { voteCounts[candidate]++; }; function getVoteCount(string memory candidate) public view returns (uint256){ return voteCounts[candidate]; }; };

When Remix compiles Solidity code, it also creates an ABI (Application Binary Interface) in JSON format. The ABI defines the interface between the smart contract and a client application.

It will specify the following:

  1. Name & type of function, event exposed by smart contract.
  2. Order of arguments for each function.
  3. The return value of each indigo.
  4. Data format of each event.

To get the ABI, copy it from within the Remix IDE. Create the file contract.abi.json in the contract at the root of the project and paste the ABI inside the file.

How to interact with smart contracts using JavaScript Picture 4

 

JavaScript has the ability to interact with smart contracts used in decentralized applications in a very simple way. Just follow the instructions above and you will be successful!

5 ★ | 1 Vote

May be interested

  • Learn about ES6 in JavascriptLearn about ES6 in Javascript
    es6 refers to version 6 of the ecma script programming language. ecma script is the standard name for javascript and version 6 is the next version after version 5, released in 2011.
  • Summary of JavaScript exercises with sample codeSummary of JavaScript exercises with sample code
    in order to make your javascript learning easier, tipsmake.com has compiled a number of javascript exercises with sample solutions for you to practice.
  • JavaScript location in HTML FileJavaScript location in HTML File
    there is flexibility in providing javascript code anywhere in an html document. however, the most preferred ways to include javascript in an html file.
  • How to Turn on JavaScriptHow to Turn on JavaScript
    javascript is a language used in many websites to provide additional functionality and access to the user. developers use javascript to deliver a large part of their site's functionality to you, the user. your browser must have javascript...
  • What is the difference between Java and JavaScript?What is the difference between Java and JavaScript?
    although the names of java and javascript seem to be related (javascript seems to be a script in java?), but that's the only similarity. these two languages ​​are not technically related to each other.
  • Void keywords in JavaScriptVoid keywords in JavaScript
    void is an important keyword in javascript that can be used as a unary operator before its single operand, which can be in any type. this operator defines an expression to be evaluated without returning a value.
  • JavaScript code to generate error charts & graphsJavaScript code to generate error charts & graphs
    the example below illustrates a sample variance chart created with javascript that incorporates a column chart. you will also get the source code for reference and editing as you wish.
  • Introduction to 2D Array - 2-dimensional array in JavaScriptIntroduction to 2D Array - 2-dimensional array in JavaScript
    in the following article, we will introduce and show you some basic operations to create and access 2-dimensional arrays - 2d array in javascript. essentially, a 2-dimensional array is a concept of a matrix of matrices - a matrix, used to store information. each 1 element contains 2 separate indexes: row (y) - column and column (x) - column.
  • Operator in JavaScriptOperator in JavaScript
    we see the following simple expression: 4 + 5 is equal to 9. here 4 and 5 are operands and '+' called operator - operator.
  • How to Disable JavaScriptHow to Disable JavaScript
    this wikihow teaches you how to turn off your web browser's javascript support. javascript is responsible for loading dynamic content in webpages, so turning it off can help websites load faster than usual. most web browsers and their...