How to Build a Decentralized Charity Platform with Next.js, TypeScript, and Solidity

Written by daltonic | Published 2024/01/16
Tech Story Tags: dapps | autonomy | solidity | typescript | decentralized-charity-platform | decentralized-charity | hackernoon-top-story | nextjs

TLDRWelcome to this comprehensive guide where we'll build a Web3 Decentralized Charity Platform using Next.js, Solidity, and TypeScript. By the end of this tutorial, you'll have a clear understanding of:via the TL;DR App

What you will be building, see the live demo at Bitfinity test network and the git repo.

Introduction

Welcome to this comprehensive guide where we'll build a Web3 Decentralized Charity Platform using Next.js, Solidity, and TypeScript. By the end of this tutorial, you'll have a clear understanding of:

  • Building dynamic interfaces with Next.js
  • Crafting Ethereum smart contracts with Solidity
  • Incorporating static type checking using TypeScript
  • Deploying and interacting with your smart contracts
  • Understanding the fundamentals of blockchain-based charity platforms

As a bonus for partaking in this tutorial, you can easily win a copy of our prestigious book on becoming an in-demand solidity developer. This offer is free for the first 300 people, for instructions on how to win watch the short video below.

Prerequisites

You will need the following tools installed to build along with me:

  • Node.js
  • Yarn
  • Git Bash
  • MetaMask
  • Next.js
  • Solidity
  • Redux Toolkit
  • Tailwind CSS

To set up MetaMask for this tutorial, please watch the instructional video below:

https://www.youtube.com/watch?v=qV1mbFOtkxo&embedable=true

Once you have completed the setup, you are eligible to receive a free copy of our book. To claim your book, please fill out the form to submit your proof-of-work.

Watch the following instructional videos to receive up to 3-months of free premium courses on

Dapp Mentors Academy, including:

Start your journey with Bitfinity today. Experience a fast, simple, and hassle-free development process as you build your first Charity Donation Tracking dApp. Deploy your smart contracts to the Bitfinity network and make a positive impact.

With that said, let’s jump into the tutorial and set up our project.

Setup

We'll start by cloning a prepared frontend repository and setting up the environment variables. Run the following commands:

git clone https://github.com/Daltonic/dappFundsX
cd dappFundsX
yarn install
git checkout no_redux_no_blockchain

Next, create a .env file at the root of the project and include the following keys:

NEXT_PUBLIC_RPC_URL=http://127.0.0.1:8545
NEXT_PUBLIC_ALCHEMY_ID=<YOUR_ALCHEMY_PROJECT_ID>
NEXT_PUBLIC_PROJECT_ID=<WALLET_CONNECT_PROJECT_ID>
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=somereallysecretsecret

Replace <YOUR_ALCHEMY_PROJECT_ID> and <WALLET_CONNECT_PROJECT_ID> with your respective project IDs.

YOUR_ALCHEMY_PROJECT_ID: Get Key Here WALLET_CONNECT_PROJECT_ID: Get Key Here

Finally, run yarn dev to start the project.

Our frontend for this project is solid and ready for some smart contract integration, but we will need Reduxify our application to enable a shared data space.

Building the Redux Store

The above image represents the structure of our Redux store, it will be simple since we are not creating some overly complex project.

We'll set up Redux to manage our application's global state. Follow these steps:

  1. Create a store folder at the project root.
  2. Inside store, create two folders: actions and states.
  3. Inside states, create a globalStates.ts file.

https://gist.github.com/Daltonic/157a49fef39e3a1ac8b9a8883c6213f8?embedable=true

  1. Inside actions, create a globalActions.ts file.

https://gist.github.com/Daltonic/c2217eff616b28a2261888ba77c236e7?embedable=true

  1. Create a globalSlices.ts file inside the store folder.

https://gist.github.com/Daltonic/69a29357cf1b9484425776a6ad4b26dd?embedable=true

  1. Create an index.ts file inside the store folder.

https://gist.github.com/Daltonic/7b3a9db8902d8ce831384ad42ca7231b?embedable=true

  1. Update the pages/_app.ts file with the Redux provider.

https://gist.github.com/Daltonic/ef67f453bc38c4038edc627644d25e2a?embedable=true

Our application has been wrapped with Redux toolkit, and we will revisit Redux when integrating the backend with the frontend.

Smart Contract Development

Next, we'll develop the smart contract for our platform:

  1. Create a contracts folder at the project root.
  2. Inside contracts, create a DappFund.sol file and add the contract code below.

https://gist.github.com/Daltonic/4e3f367d2b3a2227c951e74f4d58cbe8?embedable=true

The DappFund contract will facilitate the creation, update, and donation to charities, as well as administrative functions like changing the charity tax and banning a charity.

Here is a function-by-function breakdown:

  1. constructor(): This function sets the initial charity tax when the contract is deployed. It's executed only once during the contract's deployment.
  2. createCharity(): This function allows users to create a new charity. It requires several parameters such as the name, description, image, profile, and amount of the charity. It checks that these parameters are valid and then creates a new CharityStruct and adds it to the charities mapping.
  3. updateCharity(): This function allows the owner of a charity to update its details. It checks that the charity exists and that the sender is the owner of the charity before updating the charity's details.
  4. deleteCharity(): This function allows the owner of a charity to mark it as deleted. It checks that the charity exists and that the sender is the owner of the charity before marking it as deleted.
  5. toggleBan(): This function allows the contract owner to ban or unban a charity. It checks that the charity exists before toggling its banned status.
  6. donate(): This function allows users to donate to a charity. It checks that the charity exists, is not banned, and has not yet reached its fundraising goal. It then increments the total donation count, creates a new SupportStruct, and adds it to the supportersOf mapping. It also updates the raised amount and donation count of the charity.
  7. changeTax(): This function allows the contract owner to change the charity tax. It checks that the new tax percentage is valid before updating the tax.
  8. getCharity(): This function allows anyone to get the details of a charity. It returns the CharityStruct associated with the given ID.
  9. getCharities(): This function allows anyone to get the details of all active charities. It returns an array of CharityStruct objects.
  10. getMyCharities(): This function allows a user to get the details of all their active charities. It returns an array of CharityStruct objects.
  11. getSupports(): This function allows anyone to get the details of all supporters of a specific charity. It returns an array of SupportStruct objects.
  12. payTo(): This internal function is used to transfer funds. It sends the specified amount of Ether to the given address.
  13. currentTime(): This internal function returns the current time in seconds since the Unix Epoch. It's used to timestamp donations and charity creations.

Contract Deployment and Seeding

Now, let's deploy our smart contract and populate it with some dummy data:

  1. Create a scripts folder at the project root.
  2. Inside scripts, create a deploy.js and a seed.js file and add the following codes.

Deploy Script

https://gist.github.com/Daltonic/e4038d184c36bf69ac9b6b75da321ca1?embedable=true

Seed Script

https://gist.github.com/Daltonic/65ca0f2dfdf0ec91bfcf78f49654b36e?embedable=true

  1. Run the following commands to deploy the contract and seed it with data:

    yarn hardhat node # Run in terminal 1 
    yarn hardhat run scripts/deploy.js # Run in terminal 2 
    yarn hardhat run scripts/seed.js # Run in terminal 2
    

If you did that correctly, you should see a similar output like the one below:

At this point we can start the integration of our smart contract to our frontend.

https://www.youtube.com/watch?v=mVxRzkvX_w0&embedable=true

Frontend Integration

First, create a services folder at the project root, and inside it, create a blockchain.tsx file. This file will contain functions to interact with our smart contract.

https://gist.github.com/Daltonic/449b493fe7492386f6221329f3ee918b?embedable=true

The provided code is a TypeScript implementation of our blockchain service for interacting with our smart contract. This service enables users to perform actions on our charity platform, including creating and updating charities, making donations, and more.

Here is a function-by-function breakdown:

  1. getEthereumContracts(): This function gets the Ethereum contract instances that the service will interact with. It checks if the user has a connected Ethereum account and uses that to interact with the contract, otherwise, it uses a randomly created wallet.
  2. getAdmin(): This function returns the owner of the contract.
  3. getCharities(), getMyCharities(), getCharity(): These functions fetch all charities, the charities created by the current user, and a specific charity by its ID, respectively.
  4. getSupporters(): This function fetches the supporters of a specific charity by its ID.
  5. createCharity(), updateCharity(): These functions allow a user to create a new charity or update an existing charity, respectively.
  6. makeDonation(): This function allows a user to make a donation to a specific charity.
  7. deleteCharity(): This function allows the owner of a charity to delete it.
  8. banCharity(): This function allows the contract owner to ban a charity.
  9. structuredCharities(), structuredSupporters(): These are helper functions that structure the returned data from the contract into a more usable format.

Update the provider.tsx file inside services to include the bitfinity network using the following codes.

https://gist.github.com/Daltonic/88476a8b642f0d1f879644ce7521e735?embedable=true

Page Interacting with Smart Contract

Next, we'll link the functions in the blockchain service to their respective interfaces in the frontend:

No 1: Displaying all Charities Update pages/index.tsx to get data from the getCharities() function.

https://gist.github.com/Daltonic/c7b5205c0a352e715ea6d369c4c5a739?embedable=true

Notice how Redux is used to store blockchain data before it is displayed on the screen.

No 2: Displaying User’s Charities Update pages/projects.tsx to use the useEffect() hook to get the current user’s charities.

https://gist.github.com/Daltonic/55de269f6d41727ad2ca283adfea241e?embedable=true

Please note the use of the useEffect() hook to retrieve the current user's charities and how Redux is used to handle and display data from the blockchain across multiple components. This will be a repeated pattern across the pages and components.

No 3: Creating New Charities Update pages/donations/create.tsx to use the createCharity() function for form submission.

https://gist.github.com/Daltonic/58f3f813b5ee8bad45815545734c7410?embedable=true

No 4: Displaying Single Charity Update pages/donations/[id].tsx to use the getServerSideProps(), getCharity() and getSupporters() functions to retrieve charity and supporters by Id.

https://gist.github.com/Daltonic/96c4908e8a5406ab4e85822bb16a4b6f?embedable=true

No 5: Editing Existing Charities Update pages/donations/edit/[id].tsx to use the getCharity() function to retrieve charity by Id and populate the form fields.

https://gist.github.com/Daltonic/045ec20e60ba4aaac4d9ae62620bff51?embedable=true

Did you see how the getCharity() function was used to retrieve charity by Id and also how it was used to populate the form fields?

Components with Smart Contract

Like we did with the pages above, let’s Update the following components to interact with the smart contract:

No 1: Handling Charity Banning Update components/Ban.tsx to use the handleBanning() function to call the banCharity() function.

https://gist.github.com/Daltonic/3890759a4c5a9d83b292c1e8cbb31d91?embedable=true

No 2: Handling Charity Deletion Update components/Delete.tsx file to use the handleDelete() and deleteCharity() functions to execute a charity unlisting procedure.

https://gist.github.com/Daltonic/a9dd133448062c32990435e9a762d17d?embedable=true

No 3: Making Donations to Charities Update components/Donor.tsx file to use the handleSubmit() function to send the payment to the smart contract using the makeDonation() function.

https://gist.github.com/Daltonic/9e82883fd17884330d2a82d5cf641eae?embedable=true

Other Components

Here are the rest of the components you should also update because the integration of Redux in them.

The NavBtn Component Review and update the component that enables users to navigate, delete, and edit charity information. Utilize Redux to trigger the delete modal upon clicking.

https://gist.github.com/Daltonic/38280dec93f6046187f4e438dbbb9007?embedable=true

The Payment Component Review and update the implementation of Redux to trigger the donation, supporters, and ban modals upon clicking their respective buttons.

https://gist.github.com/Daltonic/37f2724bec3380f9ff6dbf7771278541?embedable=true

The Supports Component Review and update the implementation of Redux to close the supporters modal when the close button is clicked.

https://gist.github.com/Daltonic/59c6788386f9e0bc28b93094da25fa14?embedable=true

By implementing these updates, all components and pages are now connected to the smart contract, marking the completion of the project.

If your Nextjs server was down all this while, you can spin it up again by running yarn dev.

For further learning, we recommend watching the full video of this build on our YouTube channel.

Conclusion

In this tutorial, we've built a Decentralized Charity Platform using Next.js, Solidity, and TypeScript. We set up the development environment, built the Redux store, and deployed the smart contract to the blockchain. By integrating the smart contract with the frontend, we created a seamless user experience.

Throughout the tutorial, you gained valuable skills in building Web3 applications, crafting smart contracts, and incorporating static type checking.

Now, you're ready to create your own Decentralized Charity Platform. Happy coding and unleash your innovation in the world of Web3!



Written by daltonic | Blockchain Developer | YouTuber | Author | Educator
Published by HackerNoon on 2024/01/16