September 28, 2022

Robotic Notes

All technology News

The Definitive Guide To Building A FullStack dApp

18 min read


You probably clicked on this tutorial because you have dipped your toes into the exciting world of web3, looked at some intro resources on what web3 is, and have decided to take the next step in becoming a blockchain developer.
In this tutorial, we will explore building a complete dApp on the Ethereum network from scratch.

Overview

For the application we’ll be building, we want users that sign up to the dApp, to be able to view a list of learning resources, vote on the resources they like the most, and add their own resources to the dApp. We will start the tutorial by setting up our development environment with Hardhat, which is a development environment that allows us to build smart contracts on Ethereum easily.

After setting up our environment, we’ll build our smart contract in solidity, test that all methods are working in our terminal, deploy the contract, and connect it to our React frontend.
This is what our finished demo looks like:

null

null

Setting up our development environment

Let’s set up our development with Hardhat. We’ll use the instructions from the hardhat official documentation to set up our project

Installing Hardhat
First, navigate to the directory you would like to build your project in, create an empty directory

1mkdir resourcedapp

2cd resourcedapp

Make sure you are in the resourcedapp directory, then initialize the empty directory with the npm init command and follow the instructions on the terminal.
Now let’s install Hardhat and other Hardhat plugin dependencies that will be useful as we follow along in the tutorial.

1npm install --save-dev hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai

It might take a while for everything to be installed because of some Ethereum Javascript dependencies.

Once everything is installed, in our terminal, run the command:

This is what we get in our terminal after running the command:

Hardhat project setup

Select Create a basic sample project, leave the default hardhat config root as it is, then select yes for “Do you want to add a .gitignore” and we can see that our project has been created successfully. let’s take a look at our project structure in the next section.

Project Structure

We have everything ready to go in building our contract, but before that, let’s examine our file structure.

file structure

In our contract folder, we have the default Greeter.sol file that comes from setting up a sample project. We will be deleting it though as we will be creating our contract file for this tutorial where we will be coding our contract.
In the Script folder, we have a sample-script.js file which can be looked at as our deploy script, because it contains code to compile and deploy the contract we write.
In the test folder, we have a sample-test.js file to run our test and make sure everything is running fine before deploying the contract.
Our hardhat.config.js contains hardhat configurations for our project. Configurations like which account to deploy, which version of solidity is used in our contract, and other configurations that help in smooth dApp development.

Coding our smart contract

In the previous section we looked at the file structure, and now it’s time to begin writing our contract code.
The first thing we do is delete the greeter.sol file in the contracts folder and create a new file called Resource.sol, as this is where we will be writing our smart contract functionalities. Before jumping into the code, let’s look at the functionalities we want to achieve in the smart contract:

  • Add a new resource – To do this we will need an addResource function, that when invoked will create a new resource and add it to our array of resources.
  • List all of our resources – To do this, we will need a function getResources to list all our resources.
  • Vote on a resource – We need a voteResource function which we will pass in a particular resource id and vote on it.
  • Get a particular resource – We need a getResource function that returns a particular resource.

Solidity is an object-oriented language, if you’re familiar with Javascript or Python you won’t have much problem programming in it.

I’ll be pasting the whole contract code in the Resource.sol file we created earlier and i’ll break it down bit by bit so you see what the contract does.

1//Resource.sol

2//SPDX-License-Identifier: Unlicense

3pragma solidity ^0.8.0; // Solidity files have to start with this pragma.

4contract ResourceShare {

5 struct Resource {

6 uint8 id;

7 address creator;

8 string title;

9 string url;

10 string description;

11 uint8 total_votes;

12 }

13 mapping(uint256 => Resource) public resources;

14 event savingsEvent(uint256 indexed _resourceId);

15 uint8 public numResource;

16 constructor() {

17 numResource = 0;

18 addResource(

19 "freecodecamp",

20 "https://www.freecodecamp.org/",

21 "Learn to code"

22 );

23 }

24 function addResource(

25 string memory title,

26 string memory url,

27 string memory description

28 ) public {

29 Resource storage resource = resources[numResource];

30 resource.creator = msg.sender;

31 resource.total_votes = 0;

32 resources[numResource] = Resource(

33 numResource,

34 resource.creator,

35 title,

36 url,

37 description,

38 resource.total_votes

39 );

40 numResource++;

41 }

42 //return a particular resource

43 function getResource(uint256 resourceId)

44 public

45 view

46 returns (Resource memory)

47 {

48 return resources[resourceId];

49 }

50 //return the array of resources

51 function getResources() public view returns (Resource[] memory) {

52 Resource[] memory id = new Resource[](numResource);

53 for (uint256 i = 0; i < numResource; i++) {

54 Resource storage resource = resources[i];

55 id[i] = resource;

56 }

57 return id;

58 }

59 // Vote a resource

60 function voteResource(uint256 resourceId) public {

61 Resource storage resource = resources[resourceId];

62 resource.total_votes++;

63 }

64}

Contract Structure

1//SPDX-License-Identifier: Unlicense

2pragma solidity ^0.8.0; // Solidity files have to start with this pragma.

3contract ResourceShare {

4

5}

Solidity contracts generally start with specifying which version of solidity our contract is written in. The pragma keyword is what instructs solidity of the version we are using, in our case version 0.8.0. Next, we name our contract ResourceShare with the curly brace after. All we will be doing has to be in the curly braces.

Resource Struct
A struct in solidity is just like classes in other languages. It is used to define custom types for an entity and the attributes it might have.

1struct Resource {

2 address creator;

3 string title;

4 string url;

5 string description;

6 uint8 total_votes;

7}

In our case we have a resource struct with the following attributes:

  • id – unique id for a particular resource shared
  • creator – the creator of the resource shared
  • title – the title of our resource
  • url – the url for the resource we are sharing
  • description – the description of the resource
  • total_votes – the total votes the resource receives

Now that we have our Resource struct defined, let’s map each of our Resource and code the functionalities for the contract.

Add a Resource

1// Resource.sol

2 mapping(uint256 => Resource) public resources;

3 uint8 public numResource;

4 constructor() {

5 numResource = 0;

6 addResource(

7 "freecodecamp",

8 "https://www.freecodecamp.org/",

9 "Learn to code"

10 );

11 }

12 function addResource(

13 string memory title,

14 string memory url,

15 string memory description

16 ) public {

17 Resource storage resource = resources[numResource]; //create new instance of our resource object.

18 resource.creator = msg.sender;

19 resource.total_votes = 0;

20 resources[numResource] = Resource(

21 numResource,

22 resource.creator,

23 title,

24 url,

25 description,

26 resource.total_votes

27 );

28 numResource++;

29 }

The first line of the code in the sample above is a mapping in solidity which is like an object in Javascript used in storing data in a key-value pair format or like a hash map in some other language.

1mapping(uint256 => Resource) public resources;

In this line, we map solidity inbuilt type uint256 to our Resource struct and set to public the resources array. We create a numResource variable, which we will use to refer to the id of a resource we have in our resources array

Note 1: In solidity, using a public keyword means that the specified data can be called by anybody or any contract.

Note 2: The resources array can be populated by different resources in the image of the Resource struct we defined.

Our addResource function accepts three parameters title, url, and description. In solidity, we have to specify the type of parameters we pass into the function, and the memory keyword to store parameters temporarily in state memory.

Next, we create a new instance of our resource object in our solidity contract storage using the storage keyword. This will allow us to change the contract state directly. What we do next is set the value of what a particular resource we want to share will have.
We set the creator of the resource to always be the msg.sender, which in solidity is the person calling the functions in our contract or the person connected to our contract, and the total_votes to be zero initially. Next, we set all the values of the resource we want to share, including the arguments the user creating the resource will provide and increment numResource each time the function is called.

We can see a constructor function in the code. The constructor function is called every time we run our contract.

Get all Resources
In the previous section, we wrote the function to add a new resource. Let’s look at how to get a particular resource, then all resources in this section.

1//Resource.sol

2 //return a particular resource

3 function getResource(uint256 resourceId) public view returns (Resource memory) {

4 return resources[resourceId];

5 }

6 //return the array of resources

7 function getResources() public view returns (Resource[] memory) {

8 Resource[] memory id = new Resource[](numResource);

9 for (uint256 i = 0; i < numResource; i++) {

10 Resource storage resource = resources[i];

11 id[i] = resource;

12 }

13 return id;

14 }

In the code above, the first function getResource accepts resourceId as a parameter used to target a particular resource, then returns it. The view syntax indicates we are not making any changes to the contract state, and only viewing or querying state data. The returns syntax tells us the type of data we are returning, in our case a type of our Resource struct.
The second function getResources loops over all the resources in the array and returns them.

Voting a resource
We will make a provision for a voting function, so the user can also vote a particular resource they love.

1//Resource.sol

2 // Vote a resource

3 function voteResource(uint256 resourceId) public {

4 Resource storage resource = resources[resourceId];

5 resource.total_votes++;

6 }

This function just targets a particular resource in the contract storage and increments the total votes each time the voteResource function is called.

Deploying our contract

We are done coding our contract, it’s time to deploy it!. In this section, we will deploy the contract twice. First, we will create a local node on our machine and deploy the contract locally, then later on we will deploy the contract live to the polygon matic test network, where anyone in the world can view the contract and the transactions that happen on it. Now let’s begin.

Deploying our contract locally
To deploy our contract locally to a local node network provided by hardhat, let’s start running the node by running the command:

After running this command, Hardhat provides us with 20 accounts each with their wallet account ID and a private key. We will be using those to connect to MetaMask later on.
Each account is funded with fake 100ETH that we can use to carry out operations and pay gas fees in the dApp we are building. Here is what our terminal looks like:

null

As you can see from the image, the port our local network is running on: http://127.0.0.1:8545/.
Navigate to your hardhat.config.js and add this network configuration.

1//hardhat.config.js

2 module.exports = {

3 <------>

4 solidity: "0.8.4",

5 networks: {

6 hardhat: {

7 chainId: 31337

8 }

9 }

10};

In our script folder, rename the sample-script.js file to deploy.js as this is where we will write the script for deploying our smart contract. Tweak the deploy.js file to look like this:

1

2const hre = require("hardhat");

3async function main() {

4

5

6

7

8 const ResourceShare = await hre.ethers.getContractFactory("ResourceShare");

9 const resourceshare = await ResourceShare.deploy();

10 await resourceshare.deployed();

11 console.log("resourceshare deployed to:", resourceshare.address);

12}

13

14

15main()

16 .then(() => process.exit(0))

17 .catch((error) => {

18 console.error(error);

19 process.exit(1);

20 });

Now to finally deploy our contract we run the command

1npx hardhat run --network localhost scripts/deploy.js

When we run the above command, Hardhat automatically creates an artifacts folder at the root of our directory. The artifact folder is very important if we want to interact with the smart contract we just deployed and connect to our frontend.
This is what we get in our terminal once we have a successful deployment:

null

we can also see in the terminal tab where we started our node:

null

Above we can see different information about our deployed contract, including the contract address, the account from the 20 accounts our contract was deployed from, and gas fees used to deploy our contract.

Now that we have a successful deployment, let’s install and connect our metamask wallet to our account so we can interact with the frontend application we will be creating soon.

I’ll like for us to concentrate on the most important things, so I’ll be linking you to a guide to install and set up your metamask wallet so we can focus on the important stuff of connecting our contract to metamask.
Now that you have your metamask wallet installed, let’s connect to our Hardhat local network and import the account we deployed our contract from. Follow these steps:

  1. Click on the metamask icon on the extension tab and sign in to metamask. After signing in, you will be automatically directed to your Ethereum mainnet account.

  2. Click on the network dropdown and click on the “Add Network” button.
    null

  3. Fill in the fields with the following information and save.
    null

  4. Make sure you are now on the Hardhat network you just added, then click on the circular icon in the top right corner.
    null

  5. Go to your terminal tab where you started the Hardhat node and were provided with 20 accounts. Look for the first account, which is the account your contract was deployed from, then copy and paste it into the field that asks you to paste your private key.
    null

Click on Import and you’ll see the balance for the account you imported.

null

The balance is no longer 10000Eth as we saw from our terminal because we have used a bit of Eth to pay gas fees for deploying the contract.

Now that we have everything set up, it’s time to build our frontend and integrate it with our contract so the user can perform operations from our UI.

Building our Frontend

In the last section, we looked at how to set up our metamask wallet and import our account. Now is the time to build our frontend and interact with the contract.

We will use create-react-app to spin off a frontend at the root folder of our application.

1npx create-react-app frontend

Now that we have our frontend application set up, let’s navigate to our App.js file in the src folder and begin writing some code!.
Before jumping into some code, I’ll like to discuss how our frontend connects to our smart contract and the general structure our frontend will follow.

When building a dApp, there are helpful libraries that make it possible for us to query the blockchain for some data or make changes to a contract state in the blockchain. Examples of such libraries are web3.js, and ethers.js which are the most popular. Without these libraries, interacting with our UI will be such a pain. In our case, we are using the ethers.js library which we have already installed when starting this tutorial, and that’s why we’ll be importing it in our app.js file.

Frontend structure
We are building a resource sharing dApp, so our React frontend will have two components:

  • ListResources – This is a component of a particular resource we share in our application. It will contain all the information of the resource we share.
  • CreateResource – This component contains a form, so we can add a new resource to our app.

These two components will be imported into our App.js file.

Let’s look at what our App.js looks like:

1

2import './App.css'

3import ResourceArtifact from '../src/artifact/contracts/Resource.sol/ResourceShare.json'

4import { ethers } from 'ethers'

5import ListResources from './components/ListResources'

6import CreateResource from './components/CreateResource'

7import { useEffect, useState } from 'react'

8const resourceAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3'

9function App() {

10 const [resourceData, setResourceData] = useState([])

11 const [toggleModal, setToggleModal] = useState(false)

12 const [contract, setContract] = useState()

13 async function requestAccount() {

14 await window.ethereum.request({ method: 'eth_requestAccounts' })

15 }

16 function addResource() {

17 setToggleModal(!toggleModal)

18 }

19 const provider = new ethers.providers.Web3Provider(window.ethereum)

20 const signer = provider.getSigner()

21 async function _intializeContract(init) {

22

23

24

25 const contract = new ethers.Contract(

26 resourceAddress,

27 ResourceArtifact.abi,

28 init,

29 )

30 return contract

31 }

32 useEffect(() => {

33

34 if (typeof window.ethereum !== 'undefined') {

35 (async function getResourcesCount() {

36 await requestAccount()

37 const contract = await _intializeContract(signer)

38 const resourcedata = await contract.getResources()

39 const resources = [...resourcedata]

40 setContract(contract)

41 setResourceData(resources)

42 })()

43 }

44 }, [])

45 return (

46 <>

47 <header>

48 <button onClick={addResource}>Add a resource</button>

49 </header>

50 <main>

51 <CreateResource toggleModal={toggleModal} contract={contract} />

52 <section className="resources">

53 {resourceData.map((resource, id) => {

54 return (

55 <div key={id}>

56 <ListResources resource={resource} contract={contract} />

57 </div>

58 )

59 })}

60 </section>

61 </main>

62 </>

63 )

64}

65export default App

let’s analyze our App.js file bit by bit starting with the first 8 lines:

1import './App.css'

2import ResourceArtifact from '../src/artifact/contracts/Resource.sol/ResourceShare.json'

3import { ethers } from 'ethers'

4import ListResources from './components/ListResources'

5import CreateResource from './components/CreateResource'

6import { useEffect, useState } from 'react'

7const resourceAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3'

Above, we imported the ethers.js library we talked about earlier, our components, our contract articfact file, and our contract address.

To connect and interact with our contract, it’s a must to have the contract address and the ABI file which can be found in our artifact folder. The ABI file contains important information about our contract like the methods to call in our contract.

1const [resourceData, setResourceData] = useState([])

2 const [toggleModal, setToggleModal] = useState(false)

3 const [contract, setContract] = useState()

4 async function requestAccount() {

5 await window.ethereum.request({ method: 'eth_requestAccounts' })

6 }

Here is our application state.

  • The resourceData state will store the resource array containing all the resources.
  • The toggleModal state to hold state to decide if our modal is open or not.
  • The contract state so we can store the contract and pass it as a prop, so we can call the contract methods from other components.

Then we have the requestAccount function that calls the eth_requestAccounts method on the ethereum window object. When this method is called, the user is prompted to sign into their metamask wallet on the browser.

1const provider = new ethers.providers.Web3Provider(window.ethereum)

2 const signer = provider.getSigner()

3 async function _intializeContract(init) {

4

5

6

7 const contract = new ethers.Contract(

8 resourceAddress,

9 ResourceArtifact.abi,

10 init,

11 )

12 return contract

13 }

14 useEffect(() => {

15

16 if (typeof window.ethereum !== 'undefined') {

17 (async function getResources() {

18 await requestAccount()

19 const contract = await _intializeContract(signer)

20 const resourcedata = await contract.getResources()

21 const resources = [...resourcedata]

22 setContract(contract)

23 setResourceData(resources)

24 })()

25 }

26 }, [])

In the code above, we have an *_intializeContract* function that initializes our contract with the ethers.js library. For us to initialize the contract, we need to create a contract variable that uses the Contract method from Ethers library, which accepts three parameters:

  • The address.
  • The ResourceShare contract artifact ABI
  • The signer account that we get using window.ethereum as our provider.

Then we return the contract. We will see how the _intializeContract function would be used later.
In our React useEffect hook, we call the getResources function in an IIFE, that calls the requestAccount() function prompting the user to sign in with their Metamask, then we initialize our contract into a contract variable and call the getResources method in our contract, and set our contract and resourceData state.

1return (

2 <>

3 <header>

4 <button onClick={addResource}>Add a resource</button>

5 </header>

6 <main>

7 <CreateResource toggleModal={toggleModal} contract={contract} />

8 <section className="resources">

9 {resourceData.map((resource, id) => {

10 return (

11 <div key={id}>

12 <ListResources resource={resource} contract={contract} />

13 </div>

14 )

15 })}

16 </section>

17 </main>

18 </>

19 )

Here we return some markup of what we will display in our UI. In our header, we only have an “Add a resource” button, when clicked will call the addResource function which toggles our modal and reveals a form for us to create and add a new resource.
In the main tag, we have the CreateResource component, then we loop through our resourceData array and pass in the resource object into our ListResources component as a prop. We also pass in the contract as a prop in the two components so we can call the contract methods in the two components.

List resource Component
We looped through the resource array state in our App.js component and supplied the object prop to our ListResources component. Let’s look at what our ListResources looks like:

1function ListResources({ resource, contract }) {

2 async function vote(id) {

3 await contract.voteResource(id)

4 }

5 return (

6 <div className="project">

7 <h2>{resource.title}</h2>{' '}

8 <span className="creator">{resource.creator}</span>

9 <h3>description:</h3>

10 <p>{resource.description}</p>

11 <h4>Link:<a href={resource.url}>{resource.url}</a></h4>

12 <h4>Votes: {resource.total_votes}</h4>

13 <button

14 onClick={(id) => vote(resource.id)}

15 >

16 Vote

17 </button>

18 </div>

19 )

20}

21export default ListResources

In this component, we just accept the resource and contract prop, list display all the data in our resource object. When we click on the button we call a vote function that accepts the resource ID and calls the voteResource method in our contract incrementing the total_votes count by 1.

Create Resource Components
Our create resource components is a form modal with input fields, to add a new resource.

null

1import React, { useState } from 'react'

2

3function CreateResource({ toggleModal, contract }) {

4 const [title, setTitle] = useState('')

5 const [description, setDescription] = useState('')

6 const [url, setUrl] = useState('')

7 const handleSubmit = (event) => {

8 event.preventDefault()

9 contract.addResource(title, url, description)

10 }

11 return (

12 <div>

13 {toggleModal === true && (

14 <div className="addresource">

15 <form onSubmit={handleSubmit}>

16 <label>

17 Enter resource title:

18 <input

19 type="text"

20 value={title}

21 onChange={(e) => setTitle(e.target.value)}

22 />

23 </label>

24 <label>

25 Enter resource url:

26 <input

27 type="text"

28 value={url}

29 onChange={(e) => setUrl(e.target.value)}

30 />

31 </label>

32 <label>

33 Enter resource description:

34 <input

35 type="text"

36 value={description}

37 onChange={(e) => setDescription(e.target.value)}

38 />

39 </label>

40 <input type="submit" className="submit" />

41 </form>

42 </div>

43 )}

44 </div>

45 )

46}

47export default CreateResource

When the toggleModal state is true, this component renders conditionally. We have a state for the resource title, description, and url, and we set the state to the input value whenever our input changes. The handleSubmit function is invoked when the form is submitted, and our addResource method is called from the contract.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue.
It’s like having your browser’s inspector open while looking over your user’s shoulder.
OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams – Start monitoring your web app for free.

Deploying our contract live on a test network

In the last section, we looked at how to connect our frontend to our smart contract. In this section, we will look at how to deploy our smart contract to a live test network for everyone to see. The network we will be deploying to is the Ropsten Ethereum test network, which allows us to deploy our contract and testing it out before deploying it to the Ethereum mainnet.

First, we have to click on the metamask extension icon, then click the network dropdown and select the Ropsten test network. We need a way to interact with the Ropsten test network without running a local Ethereum node on our machine, and there are quite a few services that allow us to do that, one of them being Infura. To use the Ropsten network Ethereum node provided by Infura, we need to create an account and sign in. When signed in, click on “create a new project”

null

After clicking, you’ll be prompted by a modal asking for the project name.

null

We can name our project whatever we like and click the create button. In our project dashboard, we can see our project details and the endpoints we will be using.

null

Click on the endpoint dropdown and select Ropsten network. Now we have our project ID and the Ropsten endpoint which we will need to connect to the Ropsten network. Let’s configure Hardhat to deploy to the network. In our hardhat.config.js, we now have:

1module.exports = {

2 paths: {

3 artifacts: './frontend/src/artifact',

4 },

5 solidity: "0.8.4",

6 networks: {

7 hardhat: {

8 chainId: 31337

9 },

10 ropsten: {

11 url: "https://ropsten.infura.io/v3/ca9b0c1b342b44658282a52daaf1be25",

12 accounts: [`0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80`]

13 }

14 }

We have added a new configuration to our networks. The Ropsten network configuration requires a URL which is our ropsten endpoint gotten from Infura, and an account which is the private key of the Ropsten wallet account we selected on metamask.

null

To get the private key of the account, click on account details, then on “export private key”

null

Type in your metamask password and click confirm, then you can copy the private key and past it in your hardhat configuration. Just make sure you prefix it with 0x as seen in our Ropsten configuration

In a real-world use case where you’ll be deploying to the Ethereum mainnet, make sure the private keys are private and are stored where you can only access to prevent loss of funds. You can store it in an env file if you’d like.

We are now set to deploy the contract on the Ropsten network. All we need to do now is fund our Ropsten test network account and run the Hardhat deploy command. To fund our account, we need to paste our Ropsten testnet wallet account into a Ropsten faucet site that sends us free Ether.

null

Wait a bit, and you will see the free Ether sent to you

null

Now we can run the deploy command:

1npx hardhat run --network ropsten scripts/deploy.js

and our contract is now deployed live on the Ropsten network and you can check it out on Etherscan, a site that allows you to explore the contract you just deployed.

null

To explore our contract on Etherscan, copy the account the contract is deployed to, from the terminal and paste it on Etherscan.

null

Click on the search icon and you will see information about the contract we deployed.

null

Yay!. We have concluded the tutorial and you can find the source code here.

Conclusion

Finally, we are done with this tutorial. We learned how to build a dApp from start to finish, connect the smart contract and deploy it on a live test network, while exploring tools like Infura and Etherscan. I hope this tutorial gets you up and running building dApps on the Ethereum blockchain.



Source link