API used for communication between frontend and smart contract
Web3 js in practical (Part-III)
learn how to compile and deploy contracts using web3 js API
Background:
In web3 js (Part-II), I discussed how to compile, deploy contracts on remix IDE and interact with smart contracts using web3 js
here’s the link to web3 js (Part-II):
Now, we’ll discuss about how to generate abi, bytecode, compile, and deploy smart contracts using the web3 js library.
Pre-requisite:
Some prior knowledge is required related to:
- Advance Javascript (async-await, arrow function)
- Node JS (install, import libraries, FS module)
- Solidity (basics)
Setup environment:
There are multiple tools and options to create and set up blockchain but here are some easy steps to set up everything quickly:
- Initialize npm
create a folder, and open it with vs code or your editor. Type command in terminal:
npm init -y
- Install web3 js library
npm install web3
- Install web3-eth-contract library
npm install web3-eth-contract
- Install solidity compiler and import file system module
const solc = require('solc')
const fs = require('fs')
- setup blockchain
Ganache is a personal Ethereum blockchain that you can use to run tests, execute commands, and monitor transactions.
Download from here: https://trufflesuite.com/ganache/
After installation, open Ganache (quick start):
Coding:
create a file “index.js” in the same folder and write some code.
Import library and initialize provider (ganache network)
use the ganache network (RPC server) address in HttpProvider
Read smart contract
const fileContent = fs.readFileSync('demo.sol', 'utf8').toString();
read the smart contract from the external “demo.sol” file
Structure and compile contract
Generate ABI , bytecode and create contract instance
ABI = output.contracts["demo.sol"]["Owner"].abi;bytecode = output.contracts["demo.sol"]["Owner"].evm.bytecode.object;const contract = new Contract(ABI);
Deploy contract
here are the complete code files:
Conclusion:
I discussed how to compile and deploy smart contracts using web3 js. There are many other frameworks to deploy smart contracts like hardhat, truffle, etc.
web3 js documentation: https://web3js.readthedocs.io/en/v3.0.0-rc.5/
Wait!!! It’s too much annoying to write many lines of code just to deploy smart contracts.
Use Hardhat or truffle to test, compile, and deploy smart contracts :)
here’s the link to web3 js (Part-I):