Getting Started with Blockchain Development: A Step-by-Step Guide to Deploying Your First DApp.
Christianaojo
Posted on October 7, 2022
With the birth of Ethereum, the first programmable blockchain, web2 developers started delving into the new exciting blockchain development, dApp and the whole decentralized world. And since we are still relatively early into the web3 space, it is important, either as a web2 developer testing your feet on web3 or as a newbie just trying to get a hang around the software development to pay attention and learn the steps required for building projects on blockchain.
Creating your first and subsequent dApps requires the basic knowledge of the web3 tech stack and the steps you will use in the development. Generally, there are different stages and processes required. In this step by step guide, you will find the necessary steps, tools, and stages required for your first dApp deployment.
Is Blockchain Different From Smart Contract:
Smart contracts and blockchain are two distinct ideas that are closely related to one another. A blockchain is a type of digital network that is created and maintained by many computers running certain software. A distributed ledger tracking transactions makes up the blockchain. Such transactions' information cannot be changed once it has been entered into the system. Since blockchains are completely decentralized, no single entity has control over them.
What are dAapps and How Important Are They?
To get a full idea of what dApps means, we will need to split the word “dApp”. Breaking the word “D-app”, the ‘D’ stands for decentralized and the "app" stands for application. This already gives a much clearer meaning. Just like in web2 here we have decentralization. dApp could be a decentralized mobile application, decentralized websites, decentralized games e.t.c. Conclusively dApps are defined by interaction with the blockchain network.
In the following section, we will be building a mood detector app that communicates with the blockchain, let’s delve in.
Prerequisites:
To build a fully functioning Dapp, you will need to work on three main stages/components which require different stacks. Here are the basic pre requisites.
- First you will need to develop your application’s frontend (A basic html web page): This will come easy for you if you are a web2 developer as we will be using tech stacks you are familiar with. To do this you will need;
1. Terminal (e.g Command Prompt)
2. Code editor (e.g Visual Studio code or Atom)
3. Basic knowledge of html and CSS.
4. Install the http server. Use anything you like, but for this tutorial we will use [`lite-server`(https://www.npmjs.com/package/lite-server):
- Install Node.js ([Download and Instructions](https://nodejs.org/en/download/))
- Install Lite-server (with NPM in the terminal/command prompt):
- Next, you will need to create a basic smart contract: This will require
Create your first dApp:
We will create a mood decentralized application that simply reads and writes value to the blockchain. We will need a label, input, and buttons.
Create your dApp’s frontend
This should be a simple html webpage that displays your dApp’s user interface.
To do this:
In your terminal (for this tutorial we are using command prompt, create a new folder using the command ‘mkdir ’
In your code editor (for this tutorial we are using Visual Studio Code), open the folder you have just created in your terminal.
In your folder, create a new file called index.html
Open index.html
and then create HTML boilerplate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My First Dapp</title>
</head>
<body></body>
</html>
We will create a simple app that reads and writes value to the blockchain. We will need a label, input, and buttons.
Next, inside the body tag, add some text (Your project tittle), a label and input.
<body>
<div>
<h1>This is a Mood Decentralized App!</h1>
<p>Here we can either set or get the mood:</p>
<label for="mood">Input Mood:</label> <br />
<input type="text" id="mood" />
</div>
</body>
Then add buttons
<button onclick="getMood()">Get Mood</button>
<button onclick="setMood()">Set Mood</button>
Customize your app and make it look nicer, you can use your preferred style, color, font size and family
<head>
<style>
body {
text-align: center;
font-family: Arial, Helvetica, sans-serif;
}
div {
width: 20%;
margin: 0 auto;
display: flex;
flex-direction: column;
}
button {
width: 100%;
margin: 10px 0px 5px 0px;
}
</style>
</head>
Serve the webpage via a terminal/command prompt from the directory that has index.html
in it and run: lite-server
.
Congratulations! you have just completed stage one and your front-end is fully ready.
Go to http://127.0.0.1:3000/ in your browser to view your page!
IT’S TIME TO CREATE A BASIC SMART CONTRACT.
To create a Solidity Smart Contract, you will need an editor and for this guide we will use the online IDE Remix.
PS: Not sure how to use it then check this video
- Open Remix and ensure the "Solidity Compiler" and "Deploy and Run Transactions" tabs are present. If they are not present, enable them in the plugin manager.
It’s Now time to write your contract
- First specify the solidity version and add a license
-
Create a new solidity file in remix named
mood.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;- Define the contract
contract MoodDiary{
}
- Inside the contract create a variable called mood
string mood;
- Next, create Read and Write functions
//create a function that writes a mood to the smart contract
function setMood(string memory _mood) public{
mood = _mood;
}//create a function the reads the mood from the smart contract
function getMood() public view returns(string memory){
return mood;
}
Your Smart Contract code is now ready and all your code put together should look like this.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract MoodDiary{
}
string mood;
//create a function that writes a mood to the smart contract
function setMood(string memory _mood) public{
mood = _mood;
}
//create a function the reads the mood from the smart contract
function getMood() public view returns(string memory){
return mood;
}
Now that we have our contract ready, the next step is to deploy the contract. We will be deploying the contract on the Goerli Testnet.
To deploy your smart contract,
- Connect your Metamask to the Goerli Testnet.
- Select the correct compiler version to match the solidity contract. (In the compile tab)
Deploy the contract under the "Deploy and Run Transactions" tab
Under the Deployed Contracts section, you can test out your functions on the Remix Run tab to make sure your contract works as expected!
Congratulations!
you have now deployed your Smartcontract.
PS: Your contract will not be deployed if you do not compile it first.
Create a temporary folder to save important details.
The folder will hold
- The deployed contract's address.
- The contract ABI
Connect Your HTML Webpage to Your Deployed Smart Contract
in your local text editor in index.html
, add the following code to your html page:
Import the Ethers.js
source into your index.html
page inside a new set of script tags:
<script
src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
type="application/javascript"
></script>
<script>
////////////////////
//INPUT YOUR CODE HERE
////////////////////
</script>
Inside the script tag, import the contract ABI (what is that?) and specify the contract address on our provider's blockchain:
const MoodContractAddress = "<contract address>";
const MoodContractABI = <contract ABI>
let MoodContract;
let signer;
For the contract ABI, we want to specifically navigate to the JSON Section. We need to describe our smart contract in JSON format.
Since we have two methods, this should start as an array, with 2 objects:
const MoodContractABI = [{}, {}]
From the above page, each object should have the following fields: constant
, inputs
, name
, outputs
, payable
, stateMutability
and type
.
Your end result should look like this:
const MoodContractABI = [
{
"inputs": [],
"name": "getMood",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "string",
"name": "_mood",
"type": "string"
}
],
"name": "setMood",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
Next, Define an ethers provider. In our case, this is Goerli:
const provider = new ethers.providers.Web3Provider(window.ethereum, "goerli");
Request access to the user's wallet and connect the signer to your metamask account (we use [0]
as the default), and define the contract object using your contract address, ABI, and signer
provider.send("eth_requestAccounts", []).then(() => {
provider.listAccounts().then((accounts) => {
signer = provider.getSigner(accounts[0]);
MoodContract = new ethers.Contract(
MoodContractAddress,
MoodContractABI,
signer
);
});
});
Create asynchronous functions to call your smart contract functions
async function getMood() {
const getMoodPromise = MoodContract.getMood();
const Mood = await getMoodPromise;
console.log(Mood);
}
async function setMood() {
const mood = document.getElementById("mood").value;
const setMoodPromise = MoodContract.setMood(mood);
await setMoodPromise;
}
Connect your functions to your html buttons
<button onclick="getMood()">Get Mood</button>
<button onclick="setMood()">Set Mood</button>
After the above step, your index.html
file should have the following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My First dApp</title>
<style>
*{
background-color: beige;
font-size: larger;
}
body {
text-align: center;
font-family: Arial, Helvetica, sans-serif;
}
div {
width: 20%;
margin: 0 auto;
display: flex;
flex-direction: column;
}
p{
font-size: large;
}
button {
width: 100%;
margin: 10px 0px 5px 0px;
}
</style>
</head>
<body>
<div>
<h1>This Christie's First Decentralized App!</h1>
<p>Here we can set or get the mood:</p>
<label for="mood">Input Mood:</label> <br />
<input type="text" id="mood" />
<button onclick="getMood()">Get Mood</button>
<button onclick="setMood()">Set Mood</button>
</div>
<script
src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
type="application/javascript"
></script>
<script>
const MoodContractAddress = "0xd9145CCE52D386f254917e481eB44e9943F39138";
const MoodContractABI = [
{
"inputs": [
{
"internalType": "string",
"name": "_mood",
"type": "string"
}
],
"name": "setMood",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "getMood",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
let MoodContract;
let signer;
const provider = new ethers.providers.Web3Provider(window.ethereum, "goerli");
provider.send("eth_requestAccounts", []).then(() => {
provider.listAccounts().then((accounts) => {
signer = provider.getSigner(accounts[0]);
MoodContract = new ethers.Contract(
MoodContractAddress,
MoodContractABI,
signer
);
});
});
async function getMood() {
const getMoodPromise = MoodContract.getMood();
const Mood = await getMoodPromise;
console.log(Mood);
}
async function setMood() {
const mood = document.getElementById("mood").value;
const setMoodPromise = MoodContract.setMood(mood);
await setMoodPromise;
}
</script>
</body>
</html>
Congratulations! You now have a fully functioning decentralized application that can set or get mood.
Time to test your work.
- Got your webserver up? Go to http://127.0.0.1:3000/ in your browser to view or open your
index.html
file in your browser! - Test your functions and approve transactions as needed through Metamask. Note block times are ~15 seconds... so wait a bit to read the state of the blockchain
- See your contract and transaction info via https://goerli.etherscan.io/
- Open a console (
Ctrl + Shift + i
) in the browser to see if the magic happens as you press those buttons
Conclusion:
Celebrate! You've just created a website that communicates with an online Ethereum testnet that is operational and active. Few people can proudly claim to have done it!
In this article, we have learned about the basics of blockchain and how to create your first smart contract even if you are a complete beginner.
Resources:
Posted on October 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.