SlideShare a Scribd company logo
1/14
How to build a dApp on Avalanche blockchain
leewayhertz.com/build-dapp-on-avalanche
As we move closer to web 3.0, blockchain is more widely recognized as a key technology for
realizing the vision of a decentralized internet. The demand for a robust blockchain for dApp
and smart contract development is growing, and Ethereum is the clear favorite of developers
and businesses.
However, with most developers building on Ethereum, the costs of interacting with the
Ethereum blockchain has inflated. Those who have ever tried swapping a token on a DEX like
UniSwap knows the expense of transactions on the Ethereum blockchain.
The good news is that Ethereum is working to offset these high costs. Even many other new
blockchain protocols are also focusing on fixing the limitations of Ethereum. Avalanche is
one such protocol that addresses the issue of high transaction costs, speed, finality and other
barriers to blockchain capacity expansion. To understand the Avalanche blockchain in detail,
please refer to this article.
In this particular insight, we’ll look at Avalanche as a platform for building dApps and
understand how to build dApp on Avalanche.
What is Avalanche?
2/14
xchange
(X)
Chain
A hybrid of
three blockchains
Asset creation,
administration
and transactions.
Management of
subnets and validator
coordination.
Replicates the
Ethereum EVM for
smart contracts creation.
Platform
(P)
Chain
Contract
(C)
Chain
What is Avalanche?
LeewayHertz
Avalanche is a blockchain protocol dedicated to developing and launching DeFi dApps and
enterprise blockchain deployments. It is open-source, interoperable and scalable. Avalanche
is also known as the “blockchain of blockchains” because it is not a single blockchain like
Ethereum or Solana. Rather, it is a hybrid of three blockchains, each tailored to a distinct use
case.
Exchange (X) Chain — Supports asset creation, administration, and transactions.
Platform (P) Chain — Facilitates management of subnets and validator coordination.
Contract (C) Chain — An instance of Ethereum virtual machine for smart contracts
creation.
In this insight, we will be talking about the Contract (C) chain because it facilitates the
development of smart contracts on the Avalanche network, hence necessary for building and
deploying an application to the Avalanche blockchain.
What is the Avalanche Contract (C) Chain?
The C-Chain is a copy of the Ethereum Virtual Machine that facilitates the creation of smart
contracts. C-chain, according to Avalanche, promises better throughput, higher speed, faster
transaction confirmation times and lower fees. This is because, unlike Ethereum’s Proof-of-
Work (PoW) consensus mechanism, C-Chain uses a Proof-of-Stake (PoS) consensus
mechanism based on the Snowman Consensus Protocol. Because C-chain runs EVM under
the hood, it gives developers full access to the Ethereum developer toolset.
3/14
Modular blockchain solutions for new-age enterprise software
Build a dApp on Avalanche with LeewayHertz.
How to build dApp on Avalanche C-chain?
LeewayHertz
04
03 05
07
02 06
01
This tutorial explains how to build a simple dApp through which one can send a message to a
blockchain address, with the possibility of sending AVAX.
The development process includes the following.
Install Avalanche on your computer and run it locally.
Deploy and interact with a smart contract on the C-Chain
Create a frontent to interface for smart contracts.
Pre-Requisites for building dApp on Avalanche chain
Go, AvalancheGo, for downloading and running an Avalanche node on the local
machine
Solidity, Hardhat for building a smart contract and deploying it to the local and test
networks
4/14
React, Next.js, Ethers.js, Metamask for building a frontend to interact with smart
contract
Vercel for hosting the frontend
Note: The commands are for macOS and may differ a bit for Windows devices.
1. Run an Avalanche node on the local machine
Running a copy of the Avalanche network on your local machine is needed to develop, test,
and deploy the smart contract to the Avalanche C-Chain. You can always choose to develop
directly on the Avalanche Fuji testnet, but it is better to run a local instance as well.
For this step, get the following things installed on your computer
Go v1.17
AvalancheGo
Installing Go
To get ‘Go’ installed and configured, open a terminal and follow the steps below.
Run the following command to install Homebrew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Update Homebrew and install Go
brew update && brew install golang
Go workspace setup
mkdir -p $HOME/go/{bin,src,pkg}
Add the following to your terminal config (e.g., nano ~/.zshrc) to update your PATH
variables
export GOPATH=$HOME/go
export GOROOT="$(brew --prefix golang)/libexec"
export PATH="$PATH:${GOPATH}/bin:${GOROOT}/bin"
Install ‘gvm’ – the Go version manager, then install go1.17 and turn off GO111MODULE
bash < <(curl -s -S -L
https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
5/14
gvm install go1.17
gvm use go1.17 --default
// IMPORTANT for go versions above go1.16
export GO111MODULE="off"
Installing AvalancheGo
‘AvalancheGo’ allows you to run Avalanche on your local machine. It is the Go
implementation of an Avalanche network node. To get ‘AvalanceGo’ installed, follow the
steps below
Use ‘Go’ to clone the ava-labs/avalanchego repository.
go get -v -d
// Run the rest of the AvalancheGo commands in this location
cd $GOPATH/src/github.com/ava-labs/avalanchego
// IMPORTANT for go versions above go1.16
export GO111MODULE="on"
Build the AvalancheGo package
./scripts/build.sh
Spin up a local node
./build/avalanchego --network-id=local --staking-enabled=false --snow-sample-size=1 --
snow-quorum-size=1
2. Solidity smart contract development
Once you have got your Avalanche node running, you can now deploy smart contracts to the
C-Chain. First step is to write a smart contract.
Create a project folder
Initialize a Node.js project using ‘npm’
mkdir avalanche-dapp-tutorial && cd avalanche-dapp-tutorial
npm init -y
Store your contracts in a new folder
6/14
Install relevant packages
mkdir contracts
npm install -D @nomiclabs/hardhat-ethers @nomiclabs/hardhat-waffle avalanche
npm install -D dotenv ethereum-waffle ethers hardhat solc
Inside the contracts folder, create a .sol file for your project. Let us name it ‘ProjectA.sol
file
Open the in your editor of choice, and start writing your contract
touch contracts/ProjectA.sol
code contracts/ProjectA.sol
Next, write your own smart contract with Solidity.
3. Smart contract deployment
For smart contract deployment , you need a library called Hardhat. Hardhat act as a bridge to
the Avalanche network. If you have followed the previous steps mentioned in this tutorial,
then Hardhat library is already installed in your computer. So, you just need to add a
configuration, some npm scripts and other functions.
Add a Hardhat configuration file iIn the project root, and open it in your editor
touch hardhat.config.js
code hardhat.config.js
Import the relevant packages
require('dotenv').config()
require('@nomiclabs/hardhat-waffle')
const { task } = require('hardhat/config')... code continues
Print a list of accounts and balances on the network by adding Hardhat tasks
...
/**
This is a hardhat task to print the list of accounts on the local avalanche chain
Prints out an array of Hex addresses
7/14
*/
task('accounts', 'Prints the list of accounts', async (args, hre) => {
const accounts = await hre.ethers.getSigners()
accounts.forEach((account) => {
console.log(account.address)
})
})
/**
This is a hardhat task to print the list of accounts on the local avalanche chain as well as their
balances
Prints out an array of strings containing the address Hex and balance in Wei
*/
task(
'balances',
'Prints the list of AVAX account balances',
async (args, hre) => {
const accounts = await hre.ethers.getSigners()
for (const account of accounts) {
const balance = await hre.ethers.provider.getBalance(account.address)
console.log(${account.address} has balance ${balance.toString()})
}
}
)
... code continues
Create a ‘config’ object and configure Hardhat to use the right Avalanche networks.
8/14
const config = {
solidity: {
compilers: [{ version: '0.8.0' }],
},
networks: {
// Configure each network to the respective Avalanche instances
local: {
url: 'http://localhost:9650/ext/bc/C/rpc', // Local node we started using npm run
start:avalanche
gasPrice: 225000000000,
chainId: 43112, // Every network has a chainId for identification
accounts: [
// List of sample private keys for development accounts - DO NOT TRANSFER ASSETS TO
THESE ACCOUNTS ON A MAINNET
'0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027',
'0x7b4198529994b0dc604278c99d153cfd069d594753d471171a1d102a10438e07',
'0x15614556be13730e9e8d6eacc1603143e7b96987429df8726384c2ec4502ef6e',
'0x31b571bf6894a248831ff937bb49f7754509fe93bbd2517c9c73c4144c0e97dc',
'0x6934bef917e01692b789da754a0eae31a8536eb465e7bff752ea291dad88c675',
'0xe700bdbdbc279b808b1ec45f8c2370e4616d3a02c336e68d85d4668e08f53cff',
'0xbbc2865b76ba28016bc2255c7504d000e046ae01934b04c694592a6276988630',
'0xcdbfd34f687ced8c6968854f8a99ae47712c4f4183b78dcc4a903d1bfe8cbf60',
'0x86f78c5416151fe3546dece84fda4b4b1e36089f2dbc48496faf3a950f16157c',
'0x750839e9dbbd2a0910efe40f50b2f3b2f2f59f5580bb4b83bd8c1201cf9a010a',
],
9/14
},
fuji: {
url: 'https://api.avax-test.network/ext/bc/C/rpc', // Public Avalanche testnet
gasPrice: 225000000000,
chainId: 43113,
accounts: [], // Use your account private key on the Avalanche testnet
},
mainnet: {
url: 'https://api.avax.network/ext/bc/C/rpc', // Public Avalanche mainnet
gasPrice: 225000000000,
chainId: 43114,
accounts: [], // Use your account private key on the Avalanche mainnet
},
},
}
... code continues
Export the config
...
module.exports = config
Create ‘a /scripts’ directory and ‘a /scripts/deploy.js’ file to hold the deployed script
async function deploy() {
// Hardhat gets signers from the accounts configured in the config
const [deployer] = await hre.ethers.getSigners()
console.log('Deploying contract with the account:', deployer.address)
// Create an instance of the contract by providing the name
10/14
const ContractSource = await hre.ethers.getContractFactory('Avaxbox')
// The deployed instance of the contract
const deployedContract = await ContractSource.deploy()
console.log('Contract deployed at:', deployedContract.address)
}
deploy()
.then(() => process.exit(0))
.catch(err => {
console.error(err)
process.exit(1)
})
Open ‘package.json’ and add the following ‘npm’ scripts
...
"scripts": {
"accounts": "npx hardhat accounts",
"balances": "npx hardhat balances",
"precompile": "rimraf ./build/",
"compile": "npx hardhat compile",
"deploy": "npx hardhat run scripts/deploy.js"
},
...
Verify the working of accounts and balances scripts
npm run accounts
npm run balances
Run the ‘deploy’ command and pass in an argument to the ‘–network flag’
11/14
Here, the argument’s value should correspond to the networks defined in the
hardhart.config.js file
npm run deploy --network local
The terminal output must present results with the deployed contract address and the
address of the account deploying it.
ovie.okeh@desktop avalanche-tutorial % npm run deploy --network local
$ npx hardhat run scripts/deploy.js --network local
Deploying contract with the account: 0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC
Contract deployed at: 0xA4cD3b0Eb6E5Ab5d8CE4065BcCD70040ADAB1F00
Copy your smart contracts into Remix for quick testing and debugging.
Once your smart contract rightly works on Remix, copy it over to local contract file and
deploy it.
With this all the backend work is complete. The next step is to build the frontend to
interact with the deployed smart contract.
4. Build the dApp frontend to interact with smart contract
This part includes three steps.
Setting up Metamask
Building a frontend to interact with the smart contract
Deployment in Vercel
Setting up Metamask
Because the Avalanche C-Chain is EVM-based, you can use Metamask to interact with your
deployed contract. Metamask, a browser extension that allows you to sign and submit
transactions to an EVM-based blockchain network, is an essential component of engaging
with the smart contract from the frontend.
Metamask should be installed and configured to use the local and test networks.
Install the Metamask extenstion from the Chrome Extension Store.
Complete the Metamask configuration and connect it to the local C-Chain node.
On the Metamask extension, click the ‘Ethereum Mainnet’ toggle.
Click ‘Add Network’
Fill in the fields with the information below
12/14
Network Name: Local Avalanche C-Chain
Chain ID: 43112
Currency Symbol: AVAX
New RPC URL: http://localhost:9650/ext/bc/C/rpc
Click ‘save’
Import some test accounts and try interacting with the deployed smart contract
Open the Metamask extension
Click the ‘Account’ icon at the top right
Check if you are on the ‘Local Avalanche C-Chain’
Click ‘Import Account’
Get some private keys from config.networks.local.accounts in hardhart.config.js
Copy one private key, paste it in the field, and click ‘Import’
Building the frontend
Frontend development is very broad and vary. This particular tutorial will cover frontend
files.
The firs step is to create a ‘Next.js’ app by following the below steps.
Install React and Next.js
npm install react react-dom next
Create the below mentioned folders and files
mkdir components context pages styles utilities views
Build the following for your dApp
components
context
pages
styles
utilities
views
In the ‘package.json’ file, add the following ‘npm’ scripts
"build": "next build",
"start:client": "next start",
"start:client:dev": "next dev",
...
13/14
Deploying the dApp to Vercel
Vercel is a platform to deploy a Next.js app. Using Vercel, you can deploy your forntend it to
a public URL.
Vercel pulls your code from GitHub, so make sure that the latest version of your codes are
pushed to the Github
Log in to Vercel.com.
Create an account.
On your dashboard, click ‘New project.’
Import the frontend code from Git repository.
Review and then click ‘Deploy.’
The deployment will take some time to complete. Once its complete. you can visit your
application on a public URL.
Avalanche development services offered by LeewayHertz
LeewayHertz provides a wide range of blockchain development services to assist businesses
in adopting this cutting-edge technology and gaining significant competitive benefits. Our
team is ready to build your next winning product on Avalanche. Our portfolio of development
services.
dApps Development
Avalanche blockchain is DeFi-focused, and its anatomy is designed to power new-age DeFi
dApps. With extensive experience in creating DeFi dApps, our team is competent to best
leverage the speed, scalability and transaction finality of the network to build dApp on
Avalanche such as dApps related to trading of equities, commodities, alternative assets, and
more.
Solidity-compatible smart contract development
Our team has the advantage of having extensive experience with Ethereum toolkits, the
Solidity programming language, and the Ethereum virtual engine, all of which apply to
Avalanche development also. Thus, our developers are competent in delivering best-in-
industry solidity smart contract development services, including architecture design,
auditing, and implementation.
NFT marketplace development
Our blockchain programmers have experience creating NFT solutions for blockchain-focused
businesses. We create and launch comprehensive NFT marketplace solutions employing the
latest blockchain technology, including Avalanche, in various industries, including gaming,
14/14
arts, music, audio, start-ups, and others.
Ethereum dApps hosting on Avalanche
If you are looking forward to building Ethereum dApps, then Avalanche is the most cost-
effective and ideal decentralized smart contracts platform for building and hosting
Ethereum-compatible dApps. Our Ethereum developers can build on Avalanche using
Solidity, launch Ethereum dApp on Avalanche, run a validator, mint a token, integrate an
exchange, etc.
Custom blockchain development
We build custom blockchains, both private and public, with virtual machines in Avalanche
subnets. We provide end-to-end custom blockchain development services, including running
a node on the primary network, API calls, adding validator, subnet development and virtual
machine development.
Endnote
Avalanche is built for dApps. Its speed, low cost and eco-friendly build make it an ideal smart
contracts platform for decentralized applications. It enables the creation of solidity-
compatible dApps that immediately confirm transactions and execute thousands of them per
second. Avalanche is also an open, programable platform to build and deploy virtual
machines that can dictate operation rules for custom blockchains.
For consultancy and development services related to dApps, smart contracts and custom
blockchains development on Avalanche blockchain, please connect with our blockchain-
experts.

More Related Content

PDF
How to Build a dApp on Avalanche Full Guide 2024.pdf
PDF
How to Build a dApp on Avalanche Full Guide 2024.pdf
PPTX
How to Develop a dApp on Avalanche Blockchain?
PDF
Avalanche Blockchain Development
PPTX
Avalanche Network Explained in 8 Minutes
PDF
Programming Decentralized Application
PDF
How to Develop a dApp on Avalanche Blockchain?
PDF
Handson Smart Contract Development With Solidity And Ethereum From Fundamenta...
How to Build a dApp on Avalanche Full Guide 2024.pdf
How to Build a dApp on Avalanche Full Guide 2024.pdf
How to Develop a dApp on Avalanche Blockchain?
Avalanche Blockchain Development
Avalanche Network Explained in 8 Minutes
Programming Decentralized Application
How to Develop a dApp on Avalanche Blockchain?
Handson Smart Contract Development With Solidity And Ethereum From Fundamenta...

Similar to leewayhertz.com-How to build a dApp on Avalanche blockchain (20)

PPTX
Introduction to Avalanche — Here’s How To Buy Avalanche In Canada.pptx
PDF
Developing Blockchain Applications
PDF
Avalanche Blockchain A Game-Changer for Decentralized Finance (DeFi).pdf
PPTX
Avalanche Vs. Ethereum - How To Buy Avalanche In Canada?
PDF
iExec V3 Dev Edition - EthCC Workshop - March 2019 - Paris
PPTX
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereum
PDF
Decentralized Application: A Software Engineering Perspective
PDF
Launching a Rollup & Appchain: Everything from Idea to its Implementation
PDF
Getting Started in Blockchain Security and Smart Contract Auditing
PDF
Part 4: Understanding the working of Smart Contracts
PPTX
Avalanche-4-pub.pptx
PDF
Hyperledger Besu for Private & Public Enterprise introduction slides
PPTX
Introduction to Ethereum
PDF
Javascript toolset for Ethereum Smart Contract development
PDF
The JavaScript toolset for development on Ethereum
PPTX
Fullsize Smart Contracts That Learn
PDF
Blockchain In Action 1st Edition Bina Ramamurthy
PPTX
Ethereum Block Chain
PPTX
Ethereum Block Chain
Introduction to Avalanche — Here’s How To Buy Avalanche In Canada.pptx
Developing Blockchain Applications
Avalanche Blockchain A Game-Changer for Decentralized Finance (DeFi).pdf
Avalanche Vs. Ethereum - How To Buy Avalanche In Canada?
iExec V3 Dev Edition - EthCC Workshop - March 2019 - Paris
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereum
Decentralized Application: A Software Engineering Perspective
Launching a Rollup & Appchain: Everything from Idea to its Implementation
Getting Started in Blockchain Security and Smart Contract Auditing
Part 4: Understanding the working of Smart Contracts
Avalanche-4-pub.pptx
Hyperledger Besu for Private & Public Enterprise introduction slides
Introduction to Ethereum
Javascript toolset for Ethereum Smart Contract development
The JavaScript toolset for development on Ethereum
Fullsize Smart Contracts That Learn
Blockchain In Action 1st Edition Bina Ramamurthy
Ethereum Block Chain
Ethereum Block Chain
Ad

More from MdSaifulIslam289 (20)

PDF
Murder for hire 4 .pdf
PDF
Murder for hire 3 .pdf
PDF
Murder for hire 2 .pdf
PDF
Mian Ali Raza Sub inspector in (FIA) & CTW - Federal Investigation Agency.pdf
PDF
FIA Inspector Muhammad Noman - SHO Counter Terrorism Wing (CTW).pdf
PDF
ARSENIC REMOVAL FROM DRINKING WATER, WASTEWATER, EFFLUENT.pdf
PDF
Suns Water Theory and Study Pre-Publication in July 2024.pdf
PDF
Forex Trading Guide by FxPros.net .pdf
PDF
How to Become HIPAA Certified .pdf
PDF
ELECTRO DE IONISATION, EDI water treatment plant manufacturer for high purity...
PDF
Cosmic Origins of Space Water - Suns Water Theory.pdf
PDF
A Global Greening Initiative for Desalination_ Hydrogen and Water Production.pdf
PDF
BIO MEDICAL WASTE INCINERATOR MANUFACTURER.pdf
PDF
Report on Top 5 Sweeper Truck Manufacturers in the World.pdf
PDF
Immobilienmakler ludwigsburg.........pdf
PDF
Immobilienmakler Heilbronn...........pdf
PDF
Immobilienmakler Berlin Rudow........pdf
PDF
Jay Meeks NC rapper on the rise .pdf
PDF
Kingsway Capital Manuel Stotz e-shisha tobacco marketing memo leaked money la...
PDF
Web Design Dubai.pdf
Murder for hire 4 .pdf
Murder for hire 3 .pdf
Murder for hire 2 .pdf
Mian Ali Raza Sub inspector in (FIA) & CTW - Federal Investigation Agency.pdf
FIA Inspector Muhammad Noman - SHO Counter Terrorism Wing (CTW).pdf
ARSENIC REMOVAL FROM DRINKING WATER, WASTEWATER, EFFLUENT.pdf
Suns Water Theory and Study Pre-Publication in July 2024.pdf
Forex Trading Guide by FxPros.net .pdf
How to Become HIPAA Certified .pdf
ELECTRO DE IONISATION, EDI water treatment plant manufacturer for high purity...
Cosmic Origins of Space Water - Suns Water Theory.pdf
A Global Greening Initiative for Desalination_ Hydrogen and Water Production.pdf
BIO MEDICAL WASTE INCINERATOR MANUFACTURER.pdf
Report on Top 5 Sweeper Truck Manufacturers in the World.pdf
Immobilienmakler ludwigsburg.........pdf
Immobilienmakler Heilbronn...........pdf
Immobilienmakler Berlin Rudow........pdf
Jay Meeks NC rapper on the rise .pdf
Kingsway Capital Manuel Stotz e-shisha tobacco marketing memo leaked money la...
Web Design Dubai.pdf
Ad

Recently uploaded (20)

PDF
How to Get Funding for Your Trucking Business
PPTX
ICG2025_ICG 6th steering committee 30-8-24.pptx
PPTX
svnfcksanfskjcsnvvjknsnvsdscnsncxasxa saccacxsax
PPTX
5 Stages of group development guide.pptx
PDF
Elevate Cleaning Efficiency Using Tallfly Hair Remover Roller Factory Expertise
PDF
Unit 1 Cost Accounting - Cost sheet
PDF
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
DOCX
unit 1 COST ACCOUNTING AND COST SHEET
PDF
Stem Cell Market Report | Trends, Growth & Forecast 2025-2034
PDF
DOC-20250806-WA0002._20250806_112011_0000.pdf
PDF
Types of control:Qualitative vs Quantitative
PPTX
Probability Distribution, binomial distribution, poisson distribution
DOCX
Business Management - unit 1 and 2
DOCX
Euro SEO Services 1st 3 General Updates.docx
PDF
NISM Series V-A MFD Workbook v December 2024.khhhjtgvwevoypdnew one must use ...
PPTX
HR Introduction Slide (1).pptx on hr intro
PPTX
Principles of Marketing, Industrial, Consumers,
PPTX
2025 Product Deck V1.0.pptxCATALOGTCLCIA
PPTX
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
How to Get Funding for Your Trucking Business
ICG2025_ICG 6th steering committee 30-8-24.pptx
svnfcksanfskjcsnvvjknsnvsdscnsncxasxa saccacxsax
5 Stages of group development guide.pptx
Elevate Cleaning Efficiency Using Tallfly Hair Remover Roller Factory Expertise
Unit 1 Cost Accounting - Cost sheet
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
unit 1 COST ACCOUNTING AND COST SHEET
Stem Cell Market Report | Trends, Growth & Forecast 2025-2034
DOC-20250806-WA0002._20250806_112011_0000.pdf
Types of control:Qualitative vs Quantitative
Probability Distribution, binomial distribution, poisson distribution
Business Management - unit 1 and 2
Euro SEO Services 1st 3 General Updates.docx
NISM Series V-A MFD Workbook v December 2024.khhhjtgvwevoypdnew one must use ...
HR Introduction Slide (1).pptx on hr intro
Principles of Marketing, Industrial, Consumers,
2025 Product Deck V1.0.pptxCATALOGTCLCIA
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice

leewayhertz.com-How to build a dApp on Avalanche blockchain

  • 1. 1/14 How to build a dApp on Avalanche blockchain leewayhertz.com/build-dapp-on-avalanche As we move closer to web 3.0, blockchain is more widely recognized as a key technology for realizing the vision of a decentralized internet. The demand for a robust blockchain for dApp and smart contract development is growing, and Ethereum is the clear favorite of developers and businesses. However, with most developers building on Ethereum, the costs of interacting with the Ethereum blockchain has inflated. Those who have ever tried swapping a token on a DEX like UniSwap knows the expense of transactions on the Ethereum blockchain. The good news is that Ethereum is working to offset these high costs. Even many other new blockchain protocols are also focusing on fixing the limitations of Ethereum. Avalanche is one such protocol that addresses the issue of high transaction costs, speed, finality and other barriers to blockchain capacity expansion. To understand the Avalanche blockchain in detail, please refer to this article. In this particular insight, we’ll look at Avalanche as a platform for building dApps and understand how to build dApp on Avalanche. What is Avalanche?
  • 2. 2/14 xchange (X) Chain A hybrid of three blockchains Asset creation, administration and transactions. Management of subnets and validator coordination. Replicates the Ethereum EVM for smart contracts creation. Platform (P) Chain Contract (C) Chain What is Avalanche? LeewayHertz Avalanche is a blockchain protocol dedicated to developing and launching DeFi dApps and enterprise blockchain deployments. It is open-source, interoperable and scalable. Avalanche is also known as the “blockchain of blockchains” because it is not a single blockchain like Ethereum or Solana. Rather, it is a hybrid of three blockchains, each tailored to a distinct use case. Exchange (X) Chain — Supports asset creation, administration, and transactions. Platform (P) Chain — Facilitates management of subnets and validator coordination. Contract (C) Chain — An instance of Ethereum virtual machine for smart contracts creation. In this insight, we will be talking about the Contract (C) chain because it facilitates the development of smart contracts on the Avalanche network, hence necessary for building and deploying an application to the Avalanche blockchain. What is the Avalanche Contract (C) Chain? The C-Chain is a copy of the Ethereum Virtual Machine that facilitates the creation of smart contracts. C-chain, according to Avalanche, promises better throughput, higher speed, faster transaction confirmation times and lower fees. This is because, unlike Ethereum’s Proof-of- Work (PoW) consensus mechanism, C-Chain uses a Proof-of-Stake (PoS) consensus mechanism based on the Snowman Consensus Protocol. Because C-chain runs EVM under the hood, it gives developers full access to the Ethereum developer toolset.
  • 3. 3/14 Modular blockchain solutions for new-age enterprise software Build a dApp on Avalanche with LeewayHertz. How to build dApp on Avalanche C-chain? LeewayHertz 04 03 05 07 02 06 01 This tutorial explains how to build a simple dApp through which one can send a message to a blockchain address, with the possibility of sending AVAX. The development process includes the following. Install Avalanche on your computer and run it locally. Deploy and interact with a smart contract on the C-Chain Create a frontent to interface for smart contracts. Pre-Requisites for building dApp on Avalanche chain Go, AvalancheGo, for downloading and running an Avalanche node on the local machine Solidity, Hardhat for building a smart contract and deploying it to the local and test networks
  • 4. 4/14 React, Next.js, Ethers.js, Metamask for building a frontend to interact with smart contract Vercel for hosting the frontend Note: The commands are for macOS and may differ a bit for Windows devices. 1. Run an Avalanche node on the local machine Running a copy of the Avalanche network on your local machine is needed to develop, test, and deploy the smart contract to the Avalanche C-Chain. You can always choose to develop directly on the Avalanche Fuji testnet, but it is better to run a local instance as well. For this step, get the following things installed on your computer Go v1.17 AvalancheGo Installing Go To get ‘Go’ installed and configured, open a terminal and follow the steps below. Run the following command to install Homebrew ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Update Homebrew and install Go brew update && brew install golang Go workspace setup mkdir -p $HOME/go/{bin,src,pkg} Add the following to your terminal config (e.g., nano ~/.zshrc) to update your PATH variables export GOPATH=$HOME/go export GOROOT="$(brew --prefix golang)/libexec" export PATH="$PATH:${GOPATH}/bin:${GOROOT}/bin" Install ‘gvm’ – the Go version manager, then install go1.17 and turn off GO111MODULE bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
  • 5. 5/14 gvm install go1.17 gvm use go1.17 --default // IMPORTANT for go versions above go1.16 export GO111MODULE="off" Installing AvalancheGo ‘AvalancheGo’ allows you to run Avalanche on your local machine. It is the Go implementation of an Avalanche network node. To get ‘AvalanceGo’ installed, follow the steps below Use ‘Go’ to clone the ava-labs/avalanchego repository. go get -v -d // Run the rest of the AvalancheGo commands in this location cd $GOPATH/src/github.com/ava-labs/avalanchego // IMPORTANT for go versions above go1.16 export GO111MODULE="on" Build the AvalancheGo package ./scripts/build.sh Spin up a local node ./build/avalanchego --network-id=local --staking-enabled=false --snow-sample-size=1 -- snow-quorum-size=1 2. Solidity smart contract development Once you have got your Avalanche node running, you can now deploy smart contracts to the C-Chain. First step is to write a smart contract. Create a project folder Initialize a Node.js project using ‘npm’ mkdir avalanche-dapp-tutorial && cd avalanche-dapp-tutorial npm init -y Store your contracts in a new folder
  • 6. 6/14 Install relevant packages mkdir contracts npm install -D @nomiclabs/hardhat-ethers @nomiclabs/hardhat-waffle avalanche npm install -D dotenv ethereum-waffle ethers hardhat solc Inside the contracts folder, create a .sol file for your project. Let us name it ‘ProjectA.sol file Open the in your editor of choice, and start writing your contract touch contracts/ProjectA.sol code contracts/ProjectA.sol Next, write your own smart contract with Solidity. 3. Smart contract deployment For smart contract deployment , you need a library called Hardhat. Hardhat act as a bridge to the Avalanche network. If you have followed the previous steps mentioned in this tutorial, then Hardhat library is already installed in your computer. So, you just need to add a configuration, some npm scripts and other functions. Add a Hardhat configuration file iIn the project root, and open it in your editor touch hardhat.config.js code hardhat.config.js Import the relevant packages require('dotenv').config() require('@nomiclabs/hardhat-waffle') const { task } = require('hardhat/config')... code continues Print a list of accounts and balances on the network by adding Hardhat tasks ... /** This is a hardhat task to print the list of accounts on the local avalanche chain Prints out an array of Hex addresses
  • 7. 7/14 */ task('accounts', 'Prints the list of accounts', async (args, hre) => { const accounts = await hre.ethers.getSigners() accounts.forEach((account) => { console.log(account.address) }) }) /** This is a hardhat task to print the list of accounts on the local avalanche chain as well as their balances Prints out an array of strings containing the address Hex and balance in Wei */ task( 'balances', 'Prints the list of AVAX account balances', async (args, hre) => { const accounts = await hre.ethers.getSigners() for (const account of accounts) { const balance = await hre.ethers.provider.getBalance(account.address) console.log(${account.address} has balance ${balance.toString()}) } } ) ... code continues Create a ‘config’ object and configure Hardhat to use the right Avalanche networks.
  • 8. 8/14 const config = { solidity: { compilers: [{ version: '0.8.0' }], }, networks: { // Configure each network to the respective Avalanche instances local: { url: 'http://localhost:9650/ext/bc/C/rpc', // Local node we started using npm run start:avalanche gasPrice: 225000000000, chainId: 43112, // Every network has a chainId for identification accounts: [ // List of sample private keys for development accounts - DO NOT TRANSFER ASSETS TO THESE ACCOUNTS ON A MAINNET '0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027', '0x7b4198529994b0dc604278c99d153cfd069d594753d471171a1d102a10438e07', '0x15614556be13730e9e8d6eacc1603143e7b96987429df8726384c2ec4502ef6e', '0x31b571bf6894a248831ff937bb49f7754509fe93bbd2517c9c73c4144c0e97dc', '0x6934bef917e01692b789da754a0eae31a8536eb465e7bff752ea291dad88c675', '0xe700bdbdbc279b808b1ec45f8c2370e4616d3a02c336e68d85d4668e08f53cff', '0xbbc2865b76ba28016bc2255c7504d000e046ae01934b04c694592a6276988630', '0xcdbfd34f687ced8c6968854f8a99ae47712c4f4183b78dcc4a903d1bfe8cbf60', '0x86f78c5416151fe3546dece84fda4b4b1e36089f2dbc48496faf3a950f16157c', '0x750839e9dbbd2a0910efe40f50b2f3b2f2f59f5580bb4b83bd8c1201cf9a010a', ],
  • 9. 9/14 }, fuji: { url: 'https://api.avax-test.network/ext/bc/C/rpc', // Public Avalanche testnet gasPrice: 225000000000, chainId: 43113, accounts: [], // Use your account private key on the Avalanche testnet }, mainnet: { url: 'https://api.avax.network/ext/bc/C/rpc', // Public Avalanche mainnet gasPrice: 225000000000, chainId: 43114, accounts: [], // Use your account private key on the Avalanche mainnet }, }, } ... code continues Export the config ... module.exports = config Create ‘a /scripts’ directory and ‘a /scripts/deploy.js’ file to hold the deployed script async function deploy() { // Hardhat gets signers from the accounts configured in the config const [deployer] = await hre.ethers.getSigners() console.log('Deploying contract with the account:', deployer.address) // Create an instance of the contract by providing the name
  • 10. 10/14 const ContractSource = await hre.ethers.getContractFactory('Avaxbox') // The deployed instance of the contract const deployedContract = await ContractSource.deploy() console.log('Contract deployed at:', deployedContract.address) } deploy() .then(() => process.exit(0)) .catch(err => { console.error(err) process.exit(1) }) Open ‘package.json’ and add the following ‘npm’ scripts ... "scripts": { "accounts": "npx hardhat accounts", "balances": "npx hardhat balances", "precompile": "rimraf ./build/", "compile": "npx hardhat compile", "deploy": "npx hardhat run scripts/deploy.js" }, ... Verify the working of accounts and balances scripts npm run accounts npm run balances Run the ‘deploy’ command and pass in an argument to the ‘–network flag’
  • 11. 11/14 Here, the argument’s value should correspond to the networks defined in the hardhart.config.js file npm run deploy --network local The terminal output must present results with the deployed contract address and the address of the account deploying it. ovie.okeh@desktop avalanche-tutorial % npm run deploy --network local $ npx hardhat run scripts/deploy.js --network local Deploying contract with the account: 0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC Contract deployed at: 0xA4cD3b0Eb6E5Ab5d8CE4065BcCD70040ADAB1F00 Copy your smart contracts into Remix for quick testing and debugging. Once your smart contract rightly works on Remix, copy it over to local contract file and deploy it. With this all the backend work is complete. The next step is to build the frontend to interact with the deployed smart contract. 4. Build the dApp frontend to interact with smart contract This part includes three steps. Setting up Metamask Building a frontend to interact with the smart contract Deployment in Vercel Setting up Metamask Because the Avalanche C-Chain is EVM-based, you can use Metamask to interact with your deployed contract. Metamask, a browser extension that allows you to sign and submit transactions to an EVM-based blockchain network, is an essential component of engaging with the smart contract from the frontend. Metamask should be installed and configured to use the local and test networks. Install the Metamask extenstion from the Chrome Extension Store. Complete the Metamask configuration and connect it to the local C-Chain node. On the Metamask extension, click the ‘Ethereum Mainnet’ toggle. Click ‘Add Network’ Fill in the fields with the information below
  • 12. 12/14 Network Name: Local Avalanche C-Chain Chain ID: 43112 Currency Symbol: AVAX New RPC URL: http://localhost:9650/ext/bc/C/rpc Click ‘save’ Import some test accounts and try interacting with the deployed smart contract Open the Metamask extension Click the ‘Account’ icon at the top right Check if you are on the ‘Local Avalanche C-Chain’ Click ‘Import Account’ Get some private keys from config.networks.local.accounts in hardhart.config.js Copy one private key, paste it in the field, and click ‘Import’ Building the frontend Frontend development is very broad and vary. This particular tutorial will cover frontend files. The firs step is to create a ‘Next.js’ app by following the below steps. Install React and Next.js npm install react react-dom next Create the below mentioned folders and files mkdir components context pages styles utilities views Build the following for your dApp components context pages styles utilities views In the ‘package.json’ file, add the following ‘npm’ scripts "build": "next build", "start:client": "next start", "start:client:dev": "next dev", ...
  • 13. 13/14 Deploying the dApp to Vercel Vercel is a platform to deploy a Next.js app. Using Vercel, you can deploy your forntend it to a public URL. Vercel pulls your code from GitHub, so make sure that the latest version of your codes are pushed to the Github Log in to Vercel.com. Create an account. On your dashboard, click ‘New project.’ Import the frontend code from Git repository. Review and then click ‘Deploy.’ The deployment will take some time to complete. Once its complete. you can visit your application on a public URL. Avalanche development services offered by LeewayHertz LeewayHertz provides a wide range of blockchain development services to assist businesses in adopting this cutting-edge technology and gaining significant competitive benefits. Our team is ready to build your next winning product on Avalanche. Our portfolio of development services. dApps Development Avalanche blockchain is DeFi-focused, and its anatomy is designed to power new-age DeFi dApps. With extensive experience in creating DeFi dApps, our team is competent to best leverage the speed, scalability and transaction finality of the network to build dApp on Avalanche such as dApps related to trading of equities, commodities, alternative assets, and more. Solidity-compatible smart contract development Our team has the advantage of having extensive experience with Ethereum toolkits, the Solidity programming language, and the Ethereum virtual engine, all of which apply to Avalanche development also. Thus, our developers are competent in delivering best-in- industry solidity smart contract development services, including architecture design, auditing, and implementation. NFT marketplace development Our blockchain programmers have experience creating NFT solutions for blockchain-focused businesses. We create and launch comprehensive NFT marketplace solutions employing the latest blockchain technology, including Avalanche, in various industries, including gaming,
  • 14. 14/14 arts, music, audio, start-ups, and others. Ethereum dApps hosting on Avalanche If you are looking forward to building Ethereum dApps, then Avalanche is the most cost- effective and ideal decentralized smart contracts platform for building and hosting Ethereum-compatible dApps. Our Ethereum developers can build on Avalanche using Solidity, launch Ethereum dApp on Avalanche, run a validator, mint a token, integrate an exchange, etc. Custom blockchain development We build custom blockchains, both private and public, with virtual machines in Avalanche subnets. We provide end-to-end custom blockchain development services, including running a node on the primary network, API calls, adding validator, subnet development and virtual machine development. Endnote Avalanche is built for dApps. Its speed, low cost and eco-friendly build make it an ideal smart contracts platform for decentralized applications. It enables the creation of solidity- compatible dApps that immediately confirm transactions and execute thousands of them per second. Avalanche is also an open, programable platform to build and deploy virtual machines that can dictate operation rules for custom blockchains. For consultancy and development services related to dApps, smart contracts and custom blockchains development on Avalanche blockchain, please connect with our blockchain- experts.