Creating & Deploying a Smart Contract using Web3js & Ganache-CLI — Part 1

0
81

Note — This article is updated with the latest version of Truffle, Solidity, Metamask, web3js, and Ganache-CLI

In the earlier part, we discussed Ethereum, Smart Contract, EVM and main components of the Ethereum System.

Ethereum’ Smart Contract using Web3js & Ganache

In this part, we will implement a very Basic Decentralized App using Solidity and will use Web3/Truffle framework for development and deployment on Ganache-CLI network.

Getting Started

Basic tools we need -

  • Node Package Manager (npm) — NPM is a package manager for Node.js packages or modules.
  • Web3 js — web3js is a library which lets you interact with the blockchain through RPC. This library will be used to deploy a smart contract and interact with it.
  • Solidity — Solidity is a contract-oriented, high-level language for implementing smart contracts. It was influenced by C++, Python, and JavaScript and is designed to target the Ethereum Virtual Machine (EVM).
  • Ganache(earlier TestRPC )—Ganache is a Node.js based Ethereum client for testing and development. It runs 100% locally and simulates a full Ethereum client but is much much faster making it ideal for testing and development.
  • Truffle/Embark — Truffle/Embark is a development environment, testing framework, and asset pipeline for Ethereum. Basically, it helps you deploy your contracts to the blockchain, swap old contracts for new ones (called a migration), and hook your front-end up to your deployed contracts.
  • MetaMask/Mist — MetaMask/Mist is an Ethereum light client and Chrome extension that lets users interact with the blockchain without downloading the whole blockchain. In other words, it allows you to interact with dApps in an ordinary Chrome browser. MetaMask is dummy client to test and simulate the contract before deploying on the actual Ethereum network which is provided by Mist.
  • Visual Studio Code/Atom — Visual Studio Code is a source code editor. It supports a number of programming languages and a set of features that may or may not be available for a given language. It also has an extension for Solidity which would help us in writing Smart Contracts using this IDE.

So Let’s install our tools. We will first install npm if don’t have one. Here are instructions on how to install it.

Once npm is installed, we can use it to install ganache-cli (testrpc), a Node.js Ethereum client that mimics a real Ethereum node.

ethereumjs-testrpc has been deprecated and has been renamed to ganache-cli, So please use this package from now on.

$ npm install -g ganache-cli

Start Ganache-CLI

$ ganache-cli

or if want to run on any specific port

$ ganache-cli -p 8545

This will start up the client and generate 10 accounts for you to use, each with 100 ETH. You should see something like this:

Ganache CLI v6.4.3 (ganache-core: 2.5.5)
Available Accounts
==================
(0) 0x19e39a220bd0b32f3d0e6a01af0f2e9fc4697129 (~100 ETH)
(1) 0xb8c3dcdb4bb0b0ed66743d26313617591bb88c97 (~100 ETH)
(2) 0x27710af42d24ce6ac9a50374943ea02f825a635a (~100 ETH)
(3) 0xfa31efefdd139df83c38aa174503dee5c0d42234 (~100 ETH)
(4) 0x7c8032b0230b8998adf82ecc4aa032cfab036278 (~100 ETH)
(5) 0xa3be7fb43970d4f98866e42c554a01c2d63f3b34 (~100 ETH)
(6) 0x613b9faea2d3b109d0528f0bb989651a6e8e299b (~100 ETH)
(7) 0x3dc361390029168de15e9c6c77be46a5c35e06cf (~100 ETH)
(8) 0x85f07866d2838ae2ef5a4667dfd6dd8b9f64b812 (~100 ETH)
(9) 0x0ab839eb51c344647bef7bb7105411051dbe1823 (~100 ETH)
Private Keys
==================
(0) 0x0b6b9eebd6d3773dfbda8e4470a5d2178a736947ad25e703faf8f92b0fa8cb61
(1) 0x88c27c389c0ab6988e3195d6c2f591447873fa765fac16c8ebf2608751db3143
(2) 0xf61659cdbf45105291165b5777a9be813a567f78b54bce6e1e37004dd41498e2
(3) 0xe4d93dba856977b542daaec83b378828861cb535f7c1adcc4d42c000c6c66d9c
(4) 0x50ac5af3cbfc5fb229ba8b2c0be2f0393f350c7656d951b018c913d489affb50
(5) 0x51cb6b577668b60e54a668ca08decf4a5333575a04330b27238accfe3500c9b9
(6) 0x7ba07828a96858a4535dc29f980b90bf9e11272585c686bbfa9620dbe9639b9c
(7) 0x5c594ff0b2539148c47302b8a3cf4bcf07c03ec3f58696393cbd63ccfd091b02
(8) 0xf11424b419c7f41db179ff33c0199a5b7eccc19f0a2afe3daad8371e5e2b1341
(9) 0x0e00cb9beda393c7be54804a4b884aa579c8717dbcd832a4e8b2dc99bffa7896
HD Wallet
==================
Mnemonic: fall mushroom age arrange match tornado debris wrap sample unlock culture crime
Base HD Path: m/44'/60'/0'/0/{account_index}
Gas Price
==================
20000000000
Gas Limit
==================
6721975
Listening on 127.0.0.1:8545

The first list is the public address of each of the 10 accounts and the second list is the private key associated with each account.

Now, we will create a simple contract which will notarize a document and also check if the document is notarized. We will then first deploy this contract via Web3 and Ganache-CLI and then will use Truffle framework to do the same as Truffle framework provides few things out of the box.

Deploying using Web3 js Library and Ganache-CLI

First, install web3 js library and solidity compiler (using Solidity v0.58)

$ npm install -g web3@1.0.0-beta.37
$ npm install -g solc

To check the version of Solidity,

$ solcjs --version
0.5.8+commit.23d335f2.Emscripten.clang

Let’s create a folder with name ethereumdapp and then create subfolder contracts inside it. Now we will create a smart contract NotarizeDocument.sol inside contracts subfolder. Get the code from here.

First, we have to compile this file and create a bin(binary) and abi (Application Binary Interface)

$ solcjs --bin --abi NotarizedDocument.sol

The above command will create a binary and abi file. We can see files NotarizedDocument_sol_NotarizedDocument.bin & NotarizedDocument_sol_NotarizedDocument.abi created in contracts folder.

Now to deploy the contract we will use node and get the bytecode in node console

$ node
>bytecode=fs.readFileSync('NotarizedDocument_sol_NotarizedDocument.bin').toString()

Now we will get the abi

>abi=JSON.parse(fs.readFileSync('NotarizedDocument_sol_NotarizedDocument.abi').toString())

Once we run the above, we will see only two public functions of the contract — checkDocument and notarize.

[ { constant: true,
inputs: [ [Object] ],
name: 'checkDocument',
outputs: [ [Object] ],
payable: false,
stateMutability: 'view',
type: 'function' },
{ constant: false,
inputs: [ [Object] ],
name: 'notarize',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function' } ]

Once we have abi and bytecode, we can now deploy the contract to one of the accounts of ganache-cli.

Let's instantiate web3 with ganache (http://localhost:8545, where ganache is running). Make sure ganache is running in another terminal.

> Web3 = require('web3')
> web3 = new Web3("http://localhost:8545")

If you get an error like ‘Error: Cannot find module ‘web3’’, try installing the Web3 locally.

$ npm install web3

Web3 gives you the possibility to parse your contract ABI and provide a JavaScript API to interact with it. Then, you just need the bytecode to deploy a new instance of that contract to ganache-cli.

> notorizedContract=web3.eth.contract(abi)
> notorizedContract.deploy({data:bytecode})
.send({
from:'0x19e39a220bd0b32f3d0e6a01af0f2e9fc4697129',
gas:1500000,
gasPrice:web3.utils.toWei('0.00003', 'ether')})
.then((newContractInstance) => {notorizedContract.options.address=newContractInstance.options.address});

Once you deploy the contract, you can see a block created in ganache console something like below. It has a transaction hash and contract address.

Transaction: 0xb9c81c00b262878712af3803aba20f00562842a490c1dfc72610796b3fb00f4d
Contract created: 0x350725ed3bbb91fa64745538f2d28dd0b4375f16
Gas usage: 297522
Block Number: 1
Block Time:<>

Before invoking the methods of contracts we can check the contract address in node console to check if it matches with contract address in ganache console

> notarizedContract.options.address
'0x350725ed3bBb91Fa64745538f2D28Dd0b4375f16'

First, let's check the methods of the contracts by executing below line in node console.

> notarizedContract.methods
{ checkDocument: [Function: bound _createTxObject],
'0x53fb9233': [Function: bound _createTxObject],
'checkDocument(string)': [Function: bound _createTxObject],
notarize: [Function: bound _createTxObject],
'0x7183616c': [Function: bound _createTxObject],
'notarize(string)': [Function: bound _createTxObject] }

We can see two functions ‘checkDocument(string)’ and ‘notarize(string). Now let’s invoke these methods of the contract. Invoking ‘notarize’ function from one of the accounts of ganache-cli.

> notarizedContract.methods.notarize("Hello Romil!!").send({from:'0x19e39a220bd0b32f3d0e6a01af0f2e9fc4697129'}).then((f) => console.log(f))

Once you invoke notarize method of the contract, you can see another block created in the ganache-cli console.

Transaction: 0x94d455b45bd4d1f7434c6aee04a212bd68438bb364962c19299bad5d146c3a61
Gas usage: 44982
Block Number: 2
Block Time: <>

We can now check the document created above by calling the checkDocument method of the contract.

> notarizedContract.methods.checkDocument("Hello Romil!!").call(console.log)

This will return true in the console. If you want, you can play around with this contract and web3js. The complete code can be found here. In the next part, we will deploy the same contract using Truffle and Ganache-CLI.

Please share your thoughts, feedback, comments, and clarifications. It will help me to improvise.

If you liked this post, you can help me share it by recommending it below ❤

Follow me on Linkedin and Twitter


Creating & Deploying a Smart Contract using Web3js & Ganache-CLI — Part 1 was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.