How to build a dApp on Avalanche blockchain

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?

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.

How to build dApp on Avalanche C-chain?

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
  • 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)
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
  • 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

*/
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.
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',
],
},
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
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’
  • 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

      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",
...

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, 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.

Webinar Details

Author’s Bio

Akash Takyar
Akash Takyar
CEO LeewayHertz
Akash Takyar is the founder and CEO at LeewayHertz. The experience of building over 100+ platforms for startups and enterprises allows Akash to rapidly architect and design solutions that are scalable and beautiful.
Akash's ability to build enterprise-grade technology solutions has attracted over 30 Fortune 500 companies, including Siemens, 3M, P&G and Hershey’s. Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.

All information will be kept confidential.

 Send me the signed Non-Disclosure Agreement (NDA)

Insights

The seven layers of the metaverse

The seven layers of the metaverse

A great way to understand the metaverse is by understanding the seven layers that make it up. Every layer is important and represents a key aspect of the metaverse.

read more