Open In App

How to Deploy Contract From NodeJS using Web3?

Improve
Improve
Like Article
Like
Save
Share
Report

This article focuses on discussing deploying a contract from NodeJS using web3. The following topics will be covered in this article:

  1. Introduction to web3js modules.
  2. How to generate ABI and bytecode using web3js.
  3. Compilation and deployment of smart contracts using web3js.

Software requirements:

  1. Nodejs.
  2. Ganache.
  3. Text editor – VS Code

1. Introduction to web3.js modules

web3.js as an interface that connects our real-time world applications with the Smart contract.

When we want to connect any website with a smart contract that is deployed on the blockchain web3.js acts as an intermediatory so that they both can interact with each other. In simpler terms, in the decentralized application, we connect our frontend with the smart contract at the backend with the help of a library i.e. web3.js.

Let’s now get over to the development part.

Step 1: Create a folder of your choice and inside that add a package.json file using the command:

npm init -y

Make sure you have installed the node, you can verify it using the commands:

node -v

npm -v

 

Step 2: This package.json file will contain all installed packages, currently, it doesn’t include any package. Let’s now add web3.js to our package.json file by using the command – 

npm install –save web3

It will take some time to install so be patient. Now you might notice some changes in your folder and also the package.json file.

package.json

 

Step 3: It can be noticed that there is a dependency of web3 added along with the node modules folder created. To see what all features web3 provides let’s head towards the node terminal. The node terminal can be accessed using the command node in the command prompt.

Node command

 

Step 4: Import web3 to the terminal so that one can interact with it on the console. For this type the following command:

> let Web3 = require(“web3”);
// the variable name is starting with “W” this is because we will make a class of web3 here.

This will give undefined as output but after that type command:

> Web3

Web3

 

After typing Web3 command a bunch of code appears in the terminal and this is what the web3 library contains.

2. Interacting web3.js with Ganache

Step 1: Create web3 object and connect it with the Ganache. Before that check, Ganache is installed in the system. If Ganache is already installed then one would be able to see an HTTP URL that Ganache provides i.e. 

HTTP://127.0.0.1:7545

> let web3 = new Web3(new Web3.providers.HttpProvider(“HTTP://127.0.0.1:7545”));

Step 2: This command will give undefined as an output but after that type the command:

> web3

Step 3: Ganache can be controlled with the help of web3. Many functionalities can be used now such as to get the balance details of any account of Ganache.

> web3.eth.getBalance(“Paste any Ganache Address here”).then(function(value) {console.log(web3.utils.fromWei(value,”ether”));})

Balance

 

The output balance can be verified in Ganache for the specific address that is entered. 

3. Interacting web3.js With Smart Contracts and Compiling Smart Contracts

Step 1: In the folder create a solidity file and a JavaScript file. Here, the solidity file is named as initial.sol and javascript file as initial.js. For demonstration purposes, a small getter and setter solidity smart contract is created. Paste the smart contract into your solidity file.

Solidity




// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
 
contract initial{
 
    string public message;
 
    constructor(){
        message="Hello World";
    }
 
    function setMessage(string memory _newMessage) public{
        message=_newMessage;
    }
 
    function getMessage() public view returns(string memory){
        return message;
    }  
}


 

Project Setup in VsCode

Step 2: In Remix IDE, an ABI and a Bytecode is generated when the smart contract is compiled successfully.

ABI and Bytecode option

 

Step 3: To get the same ABI and Bytecode in the code there is a need to first install solc compiler and a file reader i.e. fs using the command:

npm install solc 

npm install  fs

Step 4: After installing solc and fs, get to the JavaScript file initial.js and make use of them.

 

Step 5: The solc, fs, web3 are imported and Ganache linked to web3.js is set up. Let’s now read the contents of the file using below command:-

node initial.js

 

Step 6: To give input to the solc compiler there is a proper input structure is required:

input to solc compiler

Input Structure of Solidity Compiler

Step 7: After giving the file input to the solc compiler, the compiler will provide us with the output, and that output needs to be converted into JSON format so as to get the ABI and Bytecode from the output.

Output to Json

Bytecode and ABI

Below is the JavaScript code for the above approach:

Javascript




// solc compiler
solc = require("solc");
 
// file reader
fs = require("fs");
 
// Creation of Web3 class
Web3 = require("web3");
 
// Setting up a HttpProvider
web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
 
// Reading the file
file = fs.readFileSync("initial.sol").toString();
console.log(file);
 
// Input structure for solidity compiler
var input = {
    language: "Solidity",
    sources: {
      "initial.sol": {
        content: file,
      },
    },
   
    settings: {
      outputSelection: {
        "*": {
          "*": ["*"],
        },
      },
    },
  };
   
  var output = JSON.parse(solc.compile(JSON.stringify(input)));
  console.log("Result : ", output);
   
  ABI = output.contracts["initial.sol"]["initial"].abi;
  bytecode = output.contracts["initial.sol"]["initial"].evm.bytecode.object;
  console.log("Bytecode: ", bytecode);
  console.log("ABI: ", ABI);


Step 8: Let’s now get the ABI and Bytecode as an output:

Bytecode

Byte Code of The Smart Contract

ABI

ABI of The Smart Contract

Now since we have successfully compiled our smart contract, let’s now deploy our smart contract.

4. Deploying Smart Contract 

Step 1: For deploying of the smart contract there is a need for a contract class instance. Let’s display all the accounts of Ganache.

Display all accounts of Ganache

Accounts Addresses of The Ganache

Step 2: To deploy the smart contract, choose an account through which the smart contract will be deployed. In this demo, the first account address is chosen.Output

Choose account to deploy smart contract

Choose the  Account Address

Below is the JavaScript code to implement the above approach: 

Javascript




// solc compiler
solc = require("solc");
 
// file reader
fs = require("fs");
 
// Creation of Web3 class
Web3 = require("web3");
 
// Setting up a HttpProvider
web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
 
// Reading the file
file = fs.readFileSync("initial.sol").toString();
 
// console.log(file);
 
// input structure for solidity compiler
var input = {
    language: "Solidity",
    sources: {
        "initial.sol": {
            content: file,
        },
    },
 
    settings: {
        outputSelection: {
            "*": {
                "*": ["*"],
            },
        },
    },
};
 
var output = JSON.parse(solc.compile(JSON.stringify(input)));
// console.log("Result : ", output);
 
ABI = output.contracts["initial.sol"]["initial"].abi;
bytecode = output.contracts["initial.sol"]["initial"].evm.bytecode.object;
// console.log("Bytecode: ", bytecode);
// console.log("ABI: ", ABI);
 
 
contract = new web3.eth.Contract(ABI);
web3.eth.getAccounts().then((accounts) => {
    // Display all Ganache Accounts
    console.log("Accounts:", accounts);
 
    mainAccount = accounts[0];
 
    // address that will deploy smart contract
    console.log("Default Account:", mainAccount);
    contract
        .deploy({ data: bytecode })
        .send({ from: mainAccount, gas: 470000 })
        .on("receipt", (receipt) => {
 
            // Contract Address will be returned here
            console.log("Contract Address:", receipt.contractAddress);
        })
        .then((initialContract) => {
            initialContract.methods.message().call((err, data) => {
                console.log("Initial Data:", data);
            });
        });
});


Output:

Output

Output

The output shows the contract address, this means that the contract is successfully deployed. The Initial Data is also printed that is set to Hello World in the smart contract. 
However, now there are tools like hardhat and truffle so there is no need to write and do all of this from scratch. 



Last Updated : 10 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads