Blockchain : Day 1 — Environment Setup

Thanh Polimi
Coinmonks
Published in
9 min readDec 30, 2021

--

Overview

As studying about blockchain technology and its applications, I decided to take note my daily experiences to share with other developers who are just like me, taking the first step in developing a decentralize applications. In this series, instead of going deeply into the concepts build up the blockchain which are very difficult, I rather prefer sharing useful developing experiences only. So as we are on the same pace, let begin.

Setting up the development environment

As you have already known, our blockchain application will be composed by a set of smart contracts. To write smart contracts, of course we need to study the smart contract programming language, but talking details about them is not in the scope of this post so let me share some keywords that you can start with :

Among them, Solidity seem to be the most well known one and we are going to use Solidity throughout this series as programming language to build our smart contracts.

Solidity is an object-oriented, high-level language for implementing smart contracts. It is influenced by C++, Python and JavaScript, and is designed to target the Ethereum Virtual Machine (EVM).

Development Environments

For development environment we have some amazing options worthy to get our hand dirty on :

It needed to be noted that Remix is rather an IDE with intuitive GUIs while others does not come with GUIs. It fosters a fast development cycle and has a rich set of plugins. It is a good place to start our entire journey of contract development as well as being a playground for learning and teaching Ethereum.

I tried both Truffle and Hardhat (not Brownie because I am not familiar with Python) but in this post, I am going to share with you the setup steps for Hardhat. Setup development environment for Truffle will be discussed in another post.

Hardhat introduction

Hardhat is a development environment to compile, deploy, test, and debug your Ethereum software. It helps developers manage and automate the recurring tasks that are inherent to the process of building smart contracts and dApps, as well as easily introducing more functionality around this workflow. This means compiling, running and testing smart contracts at the very core.

Smart Contracts at the utmost can be considered as “backend” which is going to handle some kind of business logic, and of course we need a front-end application to help us interact with smart contract. For the front-end, I am going to use the following

  • VueJS
  • web3.js

Node installation

As all of our tools based on NodeJS, we need to install NodeJS on our local. I prefer using nvm because it helps me to manage and switch between node versions very easily. As using MacOS, installing nvm is very simple

$brew update
$brew upgrade
$brew install nvm

Some of our tools are not working well with the latest version of Node, so I suggest that you should start with using Node v14.18.2 (lts/fermium) :

$nvm install lts/fermium
$nvm alias default lts/fermium
$nvm use default

Remember to check the node version before use : node --version

vue-cli installation

Install vue-cli is optional but I also suggest that as we are using vue in many others projects, vue-cli will provide a greet help

npm install -g @vue/cli
# OR
yarn global add @vue/cli

Initialize our project:

Let start by creating our first project :

$vue create hello-blockchain 
$cd hello-blockchain
$mkdir blockchain
$cd blockchain
$npm init

We first create a Vue Project using vue-cli. Vue CLI will ask us a few questions so that it can configure the front-end project for us. We then create a subfolder called blockchain and initialize it using npm . blockchain folder will be the place for holding all our smart contract development. As we are going hardhat as development environment for building our smart contract, we need to install hardhat :

$npm install --save-dev hardhat
OR
$yarn add --dev hardhat

In the same directory where you installed Hardhat run:

$npx hardhat
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
888 888 "88b 888P" d88" 888 888 "88b "88b 888
888 888 .d888888 888 888 888 888 888 .d888888 888
888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.
888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888

Welcome to Hardhat v2.8.0

? What do you want to do? …
Create a sample project
Create an advanced sample project
❯ Create an advanced sample project that use TypeScript
Quit

I suggested to start with an advanced sample project that use TypeScript. Hardhat will also ask us some simple questions to help us initialize our first project. When initialization process has finished, we can get a quick sense of what’s available and what’s going on, run npx hardhat in our project folder blockchain :

❯ npx hardhat
Hardhat version 2.8.0
Usage: hardhat [GLOBAL OPTIONS] <TASK> [TASK OPTIONS]GLOBAL OPTIONS:--config A Hardhat config file.
--emoji Use emoji in messages.
--help Shows this message, or a task's help if its name is provided
--max-memory The maximum amount of memory that Hardhat can use.
--network The network to connect to.
--show-stack-traces Show stack traces.
--tsconfig A TypeScript config file.
--verbose Enables Hardhat verbose logging
--version Shows hardhat's version.
AVAILABLE TASKS:accounts Prints the list of accounts
check Check whatever you need
clean Clears the cache and deletes all artifacts
compile Compiles the entire project, building all artifacts
console Opens a hardhat console
coverage Generates a code coverage report for tests
flatten Flattens and prints contracts and their dependencies
gas-reporter:merge
help Prints this message
node Starts a JSON-RPC server on top of Hardhat Network
run Runs a user-defined script after compiling the project
test Runs mocha tests
typechain Generate Typechain typings for compiled contracts
verify Verifies contract on Etherscan
To get help for a specific task run: npx hardhat help [task]

Local blockchain network

When we finished developing our smart contracts, we are going to deploy them on the real network but it is still the long way from now to that step. We first need to develop our smart contract and test their functionality very carefully on :

  • Local blockchain network
  • Testing purpose network ( aka TestNet like Ropsten, Rinkeby, or Kovan )

The differences of those two kind of networks is that the former lives in our personal computer while the later is really decentralized which form a staging environment. What a lucky, hardhat comes built-in with Hardhat Network, a local Ethereum network node designed for development. Hardhat Network is default used when choosing Hardhat and it can also run in a stand-alone fashion so that external clients can connect to it. This could be MetaMask, your Dapp front-end, or a script. To run Hardhat Network in this way, run:

$npx hardhat node

For some reason, I gave my heart to Ganache. Ganache is a personal blockchain for rapid Ethereum and Corda distributed application development. You can use Ganache across the entire development cycle; enabling you to develop, deploy, and test your dApps in a safe and deterministic environment.

Ganache comes in two flavors: a UI and CLI. Ganache UI is a desktop application supporting both Ethereum and Corda technology. As a fresh meat blockchain developer, I prefer using Ganache UI which can be downloaded and run easily from its official website : https://trufflesuite.com/ganache/

Truffle Ganache

By default, if you’re using Hardhat, then you’re already using Hardhat Network. When Hardhat executes your tests, scripts or tasks, an in-process Hardhat Network node is started automatically, and all of Hardhat’s plugins (ethers.js, web3.js, Waffle, Truffle, etc) will connect directly to this node’s provider. If we want hardhat to work with ganache ( or may be a test net or real net in the future ) we need to make some modification to hardhat.config.ts :

defaultNetwork: process.env.DEFAULT_NETWORK!==undefined?process.env.DEFAULT_NETWORK:'ropsten',networks: {     ganache: { 
url: process.env.GANACHE_URL || "",
accounts: process.env.GANACHE_PRIVATE_KEY !== undefined ?
[process.env.GANACHE_PRIVATE_KEY] : [],
},
},

Please being noted that we need to add 3environment variables to our .env to make it work ( It is strongly recommend that you keep your private key in .env instead of including it it config file for security reason) :

GANACHE_URL=HTTP://127.0.0.1:7545GANACHE_PRIVATE_KEY=0x4c2eb32e17d13f17b288b75efdacc105c3ae3f623210306f6551068052b0dcd7DEFAULT_NETWORK=ganache

The question is how can we find those information? The answer is we can find them on Ganache UI ( the demo image about )

  • url : RCP Server URL
  • default network : the name of used as default network in case we do not specify --network command parameters ( in this case we use ganache as the name )
  • private key : private key of the account, we are going to use to deploy the contract on ganache. From Ganache UI, click on the key icon of the account you want to use, and you will find something like below. Grab the private key and insert it into the configuration is as easy as eating a cake.

Compile the contract

Sample project come with a sample contract Greeting.sol . We are going the write a new one later but for now just use Greeting sample contract for testing. This contract can be compile using the following command

$npx hardhat compile 

Deploy the contract

If compilation went well, then we are ready to deploy our contract onto Ganache.

$npx hardhat run scripts/deploy.ts

Please noted that as we specified our default network will be ganache which is the configuration point to our Ganache UI, there is no need to use --network ganache here. If you do not want to use ganache as default network then it is necessary to tell hardhat where to deploy your contract

$npx hardhat run scripts/deploy.ts --network ropsten

If everything went well, we can verify that our contract has been successfully deployed by checking Ganache’s transaction history

  • Label : CONTRACT CREATION
  • Contract address : CREATE CONTRACT ADDRESS
  • From Address : The account that we chose to make the deployment

Interact with your contract

So your contract’s deployment went smoothly. But how can we interact with our contract? Of course we can wait for our VueJS+Web3JS being developed but it will quite a lot of time until then. What a lucky, Hardhat provide us with an useful tools call HardHat Console :

$npx hardhat console --network ganache
Hardhat console

We can interact with the blockchain network using this tools. But first, to work with the contract we need one of below hardhat’s plugins :

$npm install --save-dev @nomiclabs/hardhat-web3 web3hardhat.config.ts ADD : import "@nomiclabs/hardhat-web3";
$npm install @nomiclabs/hardhat-ethershardhat.config.tsADD : import "@nomiclabs/hardhat-ethers";

Now run console again and check available accounts

$npx hardhat console --network ganache
> let accounts = await web3.eth.getAccounts();
undefined
> accounts
[ '0x06cb429Ff34D8364fcD89D8f661084662D7Db890' ]
>

To interact with our contract :

$npx hardhat console 
> let contract = await ethers.getContractFactory('Greeter');
> const instance = await contract.attach('<contract_address>');
> let result = instance.greet();
> result
> "Hello Hardhat"
> await instance.setGreeting("Hi Dude");
> let new_result = instance.greet();
> "Hi Dude"

Please noted that you need to change the <contract_address> with the address that we found above in Ganache’s transaction history for CREATE CONTRACT ADDRESS.

End

So we finished our fist step of creating and initializing a hardhat project. We deployed the sample Greeting contract on Ganache and interacted with it through hardhat provided plugins. In the next post, I will share how to use VueJS and Web3JS to build a front-end application. See ya!

--

--

Thanh Polimi
Coinmonks

I am represented by the lion(leo), and these spirited fire signs are the kings of the celestial jungle. Leo is delighted to embrace his royal status.