
Build Your First Full Stack ‘Hello World’ dApp on Ethereum Blockchain
This is a learning by doing approach for the beginners who has a basic understanding of Ethereum Blockchain and it’s working fundamentals.
Following are the step by step procedures for Ethereum based Blockchain implementation of ‘Hello World’ dApp(Decentralized Application) with Solidity, Truffle and Web3 tech stack.
You need to have certain tools and packages installed on your local machine:-
- Install go-ethereum on your machine or Geth. You can refer https://geth.ethereum.org/docs/install-and-build/installing-geth for instructions.
- Install NodeJS on your local machine. You can refer this https://nodejs.org/en/ for further instructions.
- Install Truffle on your local machine by running
$ npm install -g truffle
Create your own Ethereum private network by creating a private single geth node:-
- Create a project called
Hello-dApp
and go to the project.Hello-dApp
is your root directory.
$ mkdir Hello-dApp
$ cd Hello-dApp
2. Create a genesis.json file by inserting following lines of code and put it in root directory. The genesis block is the start of the blockchain, and the genesis.json is the file that defines it. It is like the “settings” for your blockchain. I recommend to use Puppeth
to generate your own genesis block to have latest changes.
{
"config": {
"chainId": 2021,
"homesteadBlock": 0,
"eip150Block": 0,
"eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0,
"ethash": {}
},
"alloc": {},
"coinbase" : "0x0000000000000000000000000000000000000000",
"difficulty" : "0x400",
"extraData" : "",
"gasLimit" : "0x2fefd8",
"nonce" : "0x0000000000000042",
"mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp" : "0x00"
}
3. Create a folder named datadir
for chain data:
$ mkdir datadir
4. Initialize Blockchain network and create Genesis block
$ geth --datadir ./datadir init genesis.jsonNote: If throws error, shorten the length of root directory folder name, since Geth crashes when data-dir filepath is too long
5. Start Blockchain network and expose useful RPC APIs
$ geth --datadir ./datadir --networkid 2019 --rpc --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner" --allow-insecure-unlock
6. Now open new terminal tab with Hello-dApp
as root directory and attach to geth.ipc
$ geth attach ./datadir/geth.ipc> eth.accounts
> personal.newAccount() //Remember the passphrase
> miner.start()
> web3.personal.unlockAccount(web3.eth.accounts[0], "passphrase");Note:By default, your accounts in Geth are "locked," which means that you can't send transactions from them. You need to unlock an account in order to send transactions from it through Geth directly or via RPC (though web3 does not support this). In order to unlock an account, you'll need to provide the password, which is used to decrypt the private key associated with your account, hence allowing you to sign transactions.
With that being said, how do you unlock an account? There are a couple different ways you can do it :-geth --unlock <YOUR_ACCOUNT_ADDRESS> --password <YOUR_PASSWORD>
Unlock account from the Geth interactive Javascript console. Again, the password is optional. If you don't provide it, you'll be prompted to type it in. Note that in earlier versions of Geth, providing the password as a parameter would cause the password to show up in the Geth log, which may be a security concern.
personal.unlockAccount(address, "password")

Truffle Ethereum for Built-in support to Compile, Deploy and Link smart contracts. Truffle is just a CLI tool which helps us generate some robotic code snippets following the official Solidity Style Guide .
- Open new terminal tab with root directory and let’s use
truffle init
to initialise a project
$ truffle init
Add truffle.js
file with following code snippet in the root directory:-
module.exports = {networks: {development: {host: "127.0.0.1",port: 8545,network_id: "*", // Match any network idgas:2000000}},compilers: {solc: {version: "0.5.2"}}};
The structure of the project should now look like the following:
├── contracts
│ └── Migrations.sol
├── migrations
│ └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js3 directories, 4 files
Next, use truffle create contract HelloContract
to create a new contract.
$ truffle create contract HelloContract
The structure of the project should now look like the following:
├── contracts
│ ├── HelloContract.sol
│ └── Migrations.sol
├── migrations
│ └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js3 directories, 5 files
2. Edit HelloContract.sol
smart contract and paste the following code snippet, you’ll find it in contracts folder
pragma solidity >=0.4.22 <0.9.0;contract HelloContract {//constructor() public {//}string message = "Congratulations, you made it. Hello World!";function GetMessage() public view returns(string memory) {return message;}}
3. Go to migrations folder and edit1_initial_migration.js
file by adding following code snippet:
const Migrations = artifacts.require("Migrations");const HelloContract = artifacts.require("HelloContract.sol");var Web3 = require('web3');const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));module.exports = function(deployer) {//web3.personal.unlockAccount(web3.eth.accounts[0], “passphrase"); //Note: Please enter the same passphrase you were asked to remember //while creating this new account.deployer.deploy(Migrations);deployer.deploy(HelloContract);};
4. Include package.json
file in root directory by adding following code snippet:
{
"name": "yana",
"version": "1.0.0",
"description": "Yet Another NodeJs App",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "Anand Sinha",
"license": "ISC",
"dependencies": {
"cookie-parser": "^1.4.5",
"ejs": "^3.1.6",
"express": "^4.17.1",
"truffle-contract": "^4.0.31",
"web3": "^1.5.2"
}
}
5. Now createindex.js
file in root directory and add following code snippet for as to create a simple webpage to interact with the smart contract.
var express = require('express');var cookieParser = require('cookie-parser');var Web3 = require('web3');var contract = require('truffle-contract');var path = require('path');var provider = new Web3.providers.HttpProvider("http://localhost:8545");var app = new express();var port = 3000;app.listen(port, function(err) {if (typeof(err) == "undefined") {console.log("Your application is running on port " + port +"\nView the application in your favourite browser using url: https://127.0.0.1:3000");}});app.set('view engine', 'ejs');var ContractJSON = require(path.join(__dirname, 'build/contracts/HelloContract.json'));var Contract = contract(ContractJSON);Contract.setProvider(provider);var Res;app.get('/', function(req, result) {Contract.deployed().then(function(instance) {instance.GetMessage.call().then(function(res, err) {getname = res.toString();console.log("\nRetrieving data from Blockchain:- " + res.toString());result.render('display', {name: getname});});});});
6. Create a folder named views
in root directory and add display.ejs
file inside it including following contents:-
<!DOCTYPE html><html><head></head><body><h1><%=name%></h1></body></html>
7. Run the following commands on the terminal in project root directory to Compile and Migrate Smart Contracts to the Geth Node
$ truffle compile
$ truffle migrate
Or you can simply use:
$ truffle migrate --reset
8. Final directory structure looks like:-
├── build
├── contracts
├── datadir
├── genesis.json
├── index.js
├── migrations
├── node_modules
├── package-lock.json
├── package.json
├── test
├── truffle-config.js
├── truffle.js
└── views
Starting Node Application by opening new terminal in root directory:-
$ npm install //first time
$ npm start
Now view the application in your favourite browser using url: http://127.0.0.1:3000
Simultaneously, you can see the output on terminal too.
You get response with ‘Congratulations, you made it. Hello World!’
Well done!, we made our first dApp on Ethereum Blockchain. Congratulations!
The source code is available on this github repo:-
Attached is a quick video demonstrating how to run the application on your local system.
Updated to the latest version dated 08/16/2021
Truffle v5.4.6 (core: 5.4.6)
Solidity — 0.8.7 (solc-js)
Node v14.17.5
Web3.js v1.5.1
Want to start learning and implementing Blockchain technology? Please go through my another post on the resources regarding Blockchain:-
Please comment down your errors, doubts and suggestions regarding the implementation. Also feel free to ask if you want complete source code explanation of this implementation. Give it a clap if this helps you.
If you are stuck with something feel free to tweet me here and connect me on LinkedIn , next I shall be coming with some dApps for real use cases.
Stay tuned, stay updated. Thanks!
Hope, It helps. Enjoy Blockchain!!