Building an Ethereum Transaction App with React and Solidity: (Part Two)

daltonic

Gospel Darlington

Posted on January 17, 2022

Building an Ethereum Transaction App with React and Solidity: (Part Two)

What you’ll be building. See live demo and Git Repo Here. Remember, the online demo uses the ropsten test network.

Dalto Ethereum Transaction App

Introduction

Following part one of this tutorial, we will be building the frontend side of this project. If you haven’t seen the PART-ONE, I recommend you do it for the sake of understanding this part-two.

If you are ready, let’s crush this app…

Project Setup

Make sure you already have NodeJs installed on your machine, if you don’t, follow the link below to do that.

Jump into your projects directory and create a new folder called “dalto”. You can name it whatever you want, but for the sake of uniformity, I suggest you flow with me on the namings.

Within this dalto directory, create two more folders called client and smart_contract, our ethereum code will live in the smart_contract folder, while the react app will live in the client directory. Lastly, open this project in your code editor, I prefer VS Code. If you did all that correctly, your project structure should look like this.

Project Structure

Project Structure
The codes should be structured in the following way.

Client Structure
Smart_contract Structure

The Smart Contract Setup

Jump into the terminal, move (cd) into the smart_contract directory, and run the command below.

npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create an npm file in the root of the smart_contract folder. To specify the packages to be used for building the smart contract, we will run the code snippet below.

yarn add @nomiclabs/hardhat-ethers @nomiclabs/hardhat-waffle chai ethereum-waffle ethers hardhat --dev
# or
npm install -D @nomiclabs/hardhat-ethers @nomiclabs/hardhat-waffle chai ethereum-waffle ethers hardhat
Enter fullscreen mode Exit fullscreen mode

Please note that these packages are listed only in the development environment.
After the installation is done, you will have a result similar to mine.

Smart_contract package.json

Now you need to run the code below to set up hardhat in the current smart_contract folder.

yarn hardhat
# or
npm hardhat
Enter fullscreen mode Exit fullscreen mode

You will be prompted with some questions, you should select the following options.

  • Create a basic sample project when asked what you want to do.
  • Specify the current directory when asked for the root folder, this option is prefilled on the terminal for you.
  • Enter 'y' when asked if you want to add a .gitIgnore and hit enter on your keyboard.

Once you specify the above options properly, hardhat will automatically generate the project structure for you.

Hardhat Project Creation

Processing the Smart Contract
Next, head on to the smart_contract directory >> contracts and rename the Greeter.sol file to Transactions.sol. Afterward, paste the codes below in it, save and move along with me.

Setting up the Deployment Script
Head to smart_contract directory >> scripts and rename sample-script.js file to deploy.js. Afterward, replace the codes below in it. The code snippet below specifies where our smart contract will live on the web.

const hre = require('hardhat')
const main = async () => {
  const Transactions = await hre.ethers.getContractFactory('Transactions')
  const transactions = await Transactions.deploy()
  await transactions.deployed()
  console.log('Transactions deployed to:', transactions.address)
}
const runMain = async () => {
  try {
    await main()
    process.exit(0)
  } catch (error) {
    console.error(error)
    process.exit(1)
  }
}
runMain()
Enter fullscreen mode Exit fullscreen mode

Fantastic work, at this time you should already have your Rinkeby test network funded and ready for use, if you haven’t, please go back to the PART-ONE of this tutorial, you will find the instruction there.

Now it's time to know about alchemy

Deploying to Alchemy

Alchemy Blockchain Development and Deployment

Currently, our smart contract can only run on our computer and outsiders can’t connect to it. To make it accessible for everyone at no cost, we will use alchemy for that.

Proceed by signing up with them, or login if you already have an account.

Authentication Page

Once you are logged in, you will see the dashboard page which gives you access to create a new blockchain application.

Alchemy Dashboard

Creating an Alchemy App
Click on the CREATE APP button and fill in the details you want as seen in the image below, make sure to specify the Rinkeby test network.

Create New App Popup

After you have created the app, click on the app name or view the details button to see the app information.

Created App

Click on the VIEW KEY button and copy the HTTP URL as seen in the image below.

Created App Http Details

Fantastic, now follow the steps as seen in the images below to get your Rinkeby account. Please note, we are not using the regular account address but the private key to that account.

Step One
Step Two
Step Three

Step Four

Awesome, now go back to VS code >> smart_contract >> hardhat.config.js and replace its content with the codes below. Use your own URL in place of the existing one in the file.

require('@nomiclabs/hardhat-waffle')
module.exports = {
  solidity: '0.8.0',
  networks: {
    rinkeby: {
      url: '<YOUR_ALCHEMY_APP_URL_GOES_HERE>',
      accounts: [
        '<YOUR_RINKEBY_ACCOUNT_PRIVATE_KEY_GOES_HERE>',
      ],
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

If you had done all that correctly, we just need to do one more thing before we move on to the frontend part of this project. Let’s deploy this smart contract to Alchemy, run the code below, make sure your terminal is in the smart_contract directory.

yarn hardhat run scripts/deploy.js --network rinkeby
or
npx hardhat run scripts/deploy.js --network rinkeby
Enter fullscreen mode Exit fullscreen mode

After the smart contract is deployed successfully to Alchemy, you will have the smart contract address which you can see highlighted in the image below.

Deployed Contract

Please copy and save that address, it will later be used in the client directory >> utils >> constants.js file.

Congratulations, you just completed the smart contract deployment, now let’s use it in our frontend application.

The Frontend Setup

Using Vite React on the Frontend

Open the terminal, cd into the client directory, and perform the following instructions. For the frontend, we will use Vite to create our react application, Vite is an awesome toolset that makes the process of creating your frontend application simple.

For this build, we will also use Yarn as our primary package manager, it's just so much nicer at installing npm packages. Note, all yarn commands can easily be done with npm as well. You just need to make a small adjustment. Now let’s install Vite if you have not.

yarn create vite
# or
npm init vite@latest
Enter fullscreen mode Exit fullscreen mode

You will be prompted to enter your project name, just use “./”. This will instruct Vite to download the codes into the current directory (client). Next, you will be prompted for the project name, simply key in “dalto” and then select react from the list of frameworks available. See the image below for guidance.

Vite Installation Guide

After the above executions are done on the terminal, run the command below to install the npm modules to be used in our project.

yarn install
# or
npm install
Enter fullscreen mode Exit fullscreen mode

Installing Project Dependencies

After the process is done on the terminal, again you now have to install the following packages which our application depends on.

yarn add @heroicons/react ethers @faker-js/faker identicon.js react-hooks-global-state
# or
npm install @heroicons/react ethers @faker-js/faker identicon.js react-hooks-global-state
Enter fullscreen mode Exit fullscreen mode

If you have installed those packages, you are amazing, let’s proceed to installing the tailwind CSS which our application also depends on.

Installing Tailwind CSS

Tailwind CSS

Use the commands below to do that.

yarn add tailwindcss postcss autoprefixer --dev
yarn tailwindcss init
# or
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode

You should have two files at the root of the client folder. tailwind.config.js and postcss.config.js, but if you don’t you can create them yourself.

Next, replace the contents of the two files with the following codes.

# postcss.config.js
const tailwindcss = require('tailwindcss')
module.exports = {
  plugins: [tailwindcss('./tailwind.config.js'), require('autoprefixer')],
}


# tailwind.config.js
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

Now, replace the content of index.css file at the client directory >> src with the codes below.

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Very well, let’s test the app to see if everything is working right by running the code below.

# Running the application
yarn dev
# or
npm run dev
Enter fullscreen mode Exit fullscreen mode

If you did everything right, you should have the same result as mine.

App running

Epic work so far, let’s start coding. We will proceed by coding up the components.

Coding the Components

We have four components and we will begin with the Header component. Before we do that, go to the client directory >> src and create a folder called components. This is where all our components will reside.

Header Component

The Header Component

Create a component called Header.jsx. This component contains the send button which is used to launch the addTransactionCard modal for entering new transactions. See code block below.

Amazing, let’s create the AddTransactionCard component.

AddTransactionCard Component

Send Transaction Modal

Still, on the components directory, create another component called AddTransactionCard.jsx, afterward, paste the codes below in it and save. We will use this modal component for creating new transactions. A user can launch it whenever the send button at the Header component is clicked on.

Nice, let create the rest of the components.

Hero Component

The Hero Component

Create another component with the name Hero.jsx in the components folder. This component contains the descriptions of what this application does. It has no special functionality but assists the beauty of our app design. Paste the codes below in it and save.

Lastly, let’s create the Tabular component.

Tabular Component

The Tabular Component

Create a component with the name Tabular.jsx in the components folder and paste the codes below in it. This component is responsible for rendering all the transactions recorded in our blockchain network. Observe the code below.

All these components are unified by a single store of data using the react-hooks-global-state npm package. Now let’s bring together the above components into the App component.

The App Component

The codes below get all the components united and working together.

Cool, the above code joins all our components together, but what about the state management? How is it coupled together? Let’s look at the react-hooks-global-state store setup.

The Data Store

Go to the client >> src directory and create a folder called store. Inside this store, folder create a file called index.jsx and paste the codes below in it.

import { createGlobalState } from 'react-hooks-global-state'
const { setGlobalState, useGlobalState } = createGlobalState({
  modal: '',
  connectedAccount: '',
  transactions: [],
  transaction: {
    address: '',
    amount: '',
    remark: '',
  },
  transactionCount: localStorage.getItem('transactionCount'),
})
export { useGlobalState, setGlobalState }
Enter fullscreen mode Exit fullscreen mode

Nice, this simple state management package takes away all the complexities of Redux or the Context API. This is where we store all our transactions and keep track of the connected account.

If you’ve gotten up to this point, you deserve a cup of coffee, let’s work on the next part.

The Application Utilities

Head to the client folder >> src directory and create a new folder called utils. Now, inside of this utils folder create two files called constants.js and Transactions.json. The JSON file contains the Application Binary Interface (ABI) which was generated by hardhat and the js file will prepare it for exports.

The ABI is generated by hardhat after compilation, it describes our smart contract and prepares it in a way it can be understood by ethers.js.

On the smart_contract directory goto >> artifacts >> contracts >> Transactions.sol >> Transactions.json. You will copy the entire codes in this file and paste them in client >> src >> utils >> Transactions.json.

Next, paste the code below into the constants.js file.

import abi from './Transactions.json'
export const contractAbi = abi.abi
export const contractAddress = '<YOUR_DEPLOYED_SMART_CONTRACT_ADDRESS_GOES_HERE>'
Enter fullscreen mode Exit fullscreen mode

Awesome, I know this has been intense, but be cool, we are almost finishing up.

The Smart Contract Resources

This file provides us with all the methods available in the Transactions.sol file. These methods will help us communicate with the blockchain app using the ethers.js library and the URL we copied from Alchemy.

Create a folder named shared within client directory >> src. Create a file named Transaction.jsx and paste the codes below in it.

If your are confused about what the above functions do, please consult the PART-ONE of this tutorial here.

Download and place the following images in the client directory >> src >> assets and your done.
https://raw.githubusercontent.com/Daltonic/dalto/main/client/src/assets/ethLogo.png

https://github.com/Daltonic/dalto/blob/main/client/src/assets/logo.png?raw=true

Great, you just crushed the entire application, its time to test it out, run the code below.

yarn dev

or

npm run dev

Enter fullscreen mode Exit fullscreen mode




Conclusion

Congratulations on completing a full-fledge decentralized application with react and solidity.

Building a web3.0 app can be challenging, being that it demands a lot of skills and components, but it's not impossible.

Hopefully, the knowledge you gained from this tutorial has helped in some way. Please leave a handclap, or click on the like button to show some love.

Thanks for coding along, see you in the next tutorial…

About the Author

Gospel Darlington kick-started his journey as a software engineer in 2016. Over the years, he has grown full-blown skills in JavaScript stacks such as React, ReactNative, VueJs, and more.

He is currently freelancing, building apps for clients, writing technical tutorials teaching others how to do what he does.

Gospel Darlington is open and available to hear from you. You can reach him on LinkedIn, Facebook, Github, or on his website.

💖 💪 🙅 🚩
daltonic
Gospel Darlington

Posted on January 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related