Dapps 101: How to Build and Deploy Your First Decentralized Application
Decentralized applications, or dapps, are an exciting new paradigm enabled by blockchain technology and smart contracts. Unlike traditional apps that run on centralized servers controlled by a single company, dapps run on decentralized blockchain networks powered by cryptoeconomic incentives. This grants dapps unique properties like censorship-resistance, transparency, and tamper-proof execution.
The core components of a dapp are:
- Smart contracts – programs written in languages like Solidity that define the business logic and get deployed to a blockchain
- Frontend user interface – the client-facing portion of the dapp built using standard web technologies like HTML, CSS, and JavaScript
- Blockchain network – the underlying decentralized infrastructure, such as Ethereum, that the dapp runs on top of
When these pieces are put together, they enable powerful applications where users can trustlessly interact with each other without relying on centralized intermediaries. Use cases for dapps span areas like decentralized finance (DeFi), NFTs, gaming, social media, and more.
In this tutorial, we‘ll walk through building and deploying a basic dapp step-by-step. Our example dapp will be a simple mood tracking app where users can record and retrieve their current mood on the Ethereum blockchain.
Setting Up the Development Environment
Before diving into code, let‘s get our development environment set up. Here‘s what you‘ll need:
- Node.js and npm (node package manager) – Install from https://nodejs.org
- Metamask wallet browser extension – Allows you to interact with Ethereum dapps in your browser. Install from https://metamask.io
- Ether from a testnet faucet – Since we‘re deploying to a test network, we can get free test ether from a faucet. Try https://faucet.dimensions.network/ for Ethereum‘s Goerli testnet.
- Solidity code editor – Can use Remix web IDE at https://remix.ethereum.org or VSCode with the Solidity extension
With those installed, create a new directory for the project.
Writing the Smart Contract
The first step is to write the smart contract that will store mood entries on the blockchain. Create a new file called MoodDiary.sol and add the following code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MoodDiary {
string mood;
function setMood(string memory _mood) public {
mood = _mood;
}
function getMood() public view returns(string memory) {
return mood;
}
}
This is a very simple contract written in Solidity with two functions:
- setMood – takes in a mood string and saves it to the contract‘s state
- getMood – returns the last recorded mood
The contract also has a single state variable called mood that holds the last mood recorded.
Compiling and Deploying the Smart Contract
With our smart contract written, the next steps are to compile it and deploy it to the blockchain. We‘ll deploy to Ethereum‘s Goerli test network.
If using the Remix web IDE:
- Copy the MoodDiary.sol code into Remix
- Make sure the Solidity compiler version is set to match the pragma version at the top of the contract file
- Click the compile button
- Go to the "Deploy & Run Transactions" tab
- Select "Injected Web3" in the Environment dropdown to connect Remix to your Metamask wallet
- Select the MoodDiary contract in the Contract dropdown
- Click the Deploy button and approve the transaction from Metamask
If successful, you should see the transaction get mined and the contract will show up under "Deployed Contracts". Copy down the contract address as we‘ll need that later.
Building the Frontend UI
Now that our contract is deployed, let‘s build a minimal frontend for interacting with it. Create two files: index.html and main.js.
In index.html, add 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>Mood Diary Dapp</title>
</head>
<body>
<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 id="moodDisplay"></div>
<script
src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
type="application/javascript"
></script>
<script src="main.js"></script>
</body>
</html>
This loads ethers.js, a library that allows us to interact with our smart contract, and adds elements for displaying and setting the mood.
In main.js, add this code:
const MoodContractAddress = "your-contract-address";
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"
}
];
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;
document.getElementById("moodDisplay").innerText = `Your current mood: ${mood}`;
}
async function setMood() {
const mood = document.getElementById("mood").value;
const setMoodPromise = MoodContract.setMood(mood);
await setMoodPromise;
}
Be sure to replace "your-contract-address" with the real address of your deployed MoodDiary contract. You can get the contract ABI, which tells ethers.js how to interact with the contract, from the Solidity compiler tab in Remix.
Walking through this code:
- We first define variables for the contract address and ABI
- We initialize a provider to connect to the blockchain and prompt the user to connect their Metamask wallet
- Once the wallet is connected, we get the signer object which allows us to send transactions
- The getMood function calls the getMood function in our smart contract and displays the returned value
- The setMood function takes the user‘s input, sends it to the setMood function in the contract, and waits for the transaction to be mined
At this point, open index.html in your browser, connect your Metamask wallet, and test out the app! Try setting a mood and then clicking "Get Mood" to retrieve it.
Deploying to a Live Network
Deploying your dapp to a live Ethereum network like mainnet or one of the major testnets is very similar to deploying to your local test network. The main differences are:
- You‘ll need real ETH to pay for gas on a live network. Be sure to get some from an exchange or faucet first.
- The contract address and network name will change. Point to the new contract address in main.js and use the correct network name when initializing the ethers.js provider.
- You may want to host your frontend rather than just opening a local file. You can use free services like GitHub Pages or IPFS to host your dapp‘s frontend files.
After updating those items, your dapp will be live on a public blockchain for anyone to access and interact with!
The Future of Dapps
We‘ve only scratched the surface of what‘s possible with dapps and Web3. As blockchain technology and developer tooling continue to mature, we‘ll see more and more user-friendly dapps emerge that challenge centralized Web2 incumbents.
Some exciting areas to watch in the dapp space are:
- DeFi – dapps for lending, borrowing, trading, saving, etc. in crypto with no financial intermediaries
- NFTs – owning and trading provably unique digital assets
- DAOs – decentralized, internet-native organizations for collaborating and pooling capital
- Blockchain gaming – games with player ownership of in-game assets and decentralized game economies
The dapp ecosystem is still in its early stages but has a bright future ahead. Web3 promises a more open, transparent, and user-controlled Internet – and dapps built on blockchains like Ethereum are leading the charge.
To learn more about dapps and blockchain development, I recommend exploring these resources:
- CryptoZombies – Interactive code school for learning Ethereum and Solidity
- Ethereum.org Developer Portal – Guides, tutorials, and documentation for Ethereum developers
- Solidity Docs – Main documentation site for the Solidity smart contract language
- OpenZeppelin – Library of secure, audited smart contract templates to build on
- Alchemy – Developer tools and infrastructure for web3 with good tutorials