paint-brush
How to Build a Decentralized House Rental Platform with Next.js, Redux, and Solidityby@daltonic
222 reads

How to Build a Decentralized House Rental Platform with Next.js, Redux, and Solidity

by Darlington Gospel January 29th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

By the end of this guide, you will have a functioning decentralized platform where users can list and rent houses, all managed and secured by Ethereum smart contracts.
featured image - How to Build a Decentralized House Rental Platform with Next.js, Redux, and Solidity
Darlington Gospel  HackerNoon profile picture



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


House Rental Marketplace


House Rental Marketplace

Introduction

Welcome to our second comprehensive guide on “Building a Decentralized House Rental Platform with Next.js, Redux, and Solidity”. We'll be developing a Decentralized House Rental Platform using Next.js, Solidity, and TypeScript. Throughout this tutorial, you'll gain a clear understanding of the following:


  • 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 rental platforms


By the end of this guide, you will have a functioning decentralized platform where users can list and rent houses, all managed and secured by Ethereum smart contracts.


As an added incentive for participating in this tutorial, we're giving away a copy of our prestigious book on becoming an in-demand Solidity developer. This offer is free for the first 300 participants. For instructions on how to claim your copy, please watch the short video below.


Capturing Smart Contract Development

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:


Once you have successfully 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.


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/dappBnbX
cd dappBnbX
yarn install
git checkout no_redux


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.


Dummy Data


Our frontend is ready for smart contract integration, but we need to implement Redux to enable shared data space.

Building the Redux Store

Store Structure


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.js file.

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

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

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

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

We have implemented Redux toolkit in our application and plan to revisit its usage 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 DappBnb.sol file and add the contract code below.

The DappBnb contract represents a decentralized house rental platform where users can list apartments for rent, book available apartments, and leave reviews.


Let's go through each part of the contract:

  1. Contract Setup and Libraries: The contract imports Ownable, Counters, and ReentrancyGuard from the OpenZeppelin library. Ownable provides basic authorization control functions, Counters is used for counting variables, and ReentrancyGuard helps prevent re-entrancy attacks.
  2. Struct Definitions: The contract defines three structs: ApartmentStruct, BookingStruct, and ReviewStruct. These define the data structures for apartments, bookings, and reviews respectively.
  3. State Variables: The contract declares several state variables, including security fees, tax percentages, and mappings to keep track of apartments, bookings, reviews, and other related data.
  4. Constructor: The constructor function initializes the taxPercent and securityFee state variables.
  5. Apartment Functions: Functions like createApartment, updateApartment, deleteApartment, getApartments, and getApartment are used to manage apartment listings on the platform.
  6. Booking Functions: Functions like bookApartment, checkInApartment, claimFunds, refundBooking, getUnavailableDates, getBookings, getQualifiedReviewers, and getBooking are used to manage the booking process and interactions between tenants and apartment owners.
  7. Review Functions: The addReview and getReviews functions manage the review process, allowing tenants to leave reviews for apartments they've booked.
  8. Utility Functions: The payTo and currentTime functions are utility functions used in multiple other functions. payTo is used to transfer funds between addresses, and currentTime returns the current block timestamp.

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

Seed Script

  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:


Deployment


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

Frontend Integration

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

The above script is a service that interacts with a smart contract deployed on the chain. In a joint effort with EthersJs, it provides functions to read and write data on the blockchain via the contract's methods.


Here's a breakdown of the functions:

  1. getEthereumContracts: This function establishes a connection to the Ethereum network either through a browser provider (if available) or via a JSON-RPC endpoint. It then creates an instance of the smart contract using its ABI and address. If a user is connected via their wallet, the contract instance is linked to the user's account. Otherwise, a random account is generated and linked to the contract.
  2. getApartments, getApartment: These functions fetch all apartments and a specific apartment respectively from the smart contract.
  3. getBookings: Fetches all bookings for a specific apartment from the smart contract.
  4. getQualifiedReviewers: Fetches all addresses that are qualified to leave reviews for a specific apartment.
  5. getReviews: Fetches all reviews for a specific apartment from the smart contract.
  6. getBookedDates: Fetches all dates that are booked for a specific apartment from the smart contract.
  7. getSecurityFee: Fetches the security fee from the smart contract.
  8. createApartment, updateApartment, deleteApartment: These functions allow a user to create, update, and delete apartments respectively.
  9. bookApartment: This function allows a user to book an apartment for specific dates.
  10. checkInApartment: This function allows a user to check into an apartment.
  11. refundBooking: This function allows a user to get a refund for a booking.
  12. addReview: This function allows a user to add a review for an apartment.

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

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 Available Apartments Update pages/index.jsx to get data from the getApartments() function.

No 2: Displaying Single Apartment Update pages/room/[roomId].jsx to use the getServerSideProps(), getApartment(), getBookedDates() and the other functions to retrieve apartment and booking details by the room’s Id.

No 3: Creating New Apartments Update pages/room/add.jsx to use the createApartment() function for form submission.

No 4: Editing Existing Apartments Update pages/room/edit/[roomId].jsx to use the getApartment() function to retrieve apartment by Id and populate the form fields.

No 5: Displaying All Bookings Update pages/bookings/roomId.jsx to get data from the getApartment() and getBookings() functions.

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 Apartment Deletion Update components/Actions.jsx file to use the handleDelete() function to call the deleteApartment() functions.

No 2: Adding Reviews to Apartment Update components/AddReview.jsx modal to use the handleSubmit() function to call the addReview() function.

Observe how Redux was used to open and close the review modal.


No 3: Adding Reviews to Apartment Update components/Booking.jsx file to use the handleCheckIn() and handleRefund() functions.

No 4: Adding Reviews to Apartment Lastly, update components/Calendar.jsx file to use the handleSubmit() function to call the bookApartment() function.

Also notice that we are using Redux to retrieve the security fee which is necessary to calculate the cost of booking an apartment.


The project is now complete as all components and pages are connected to the smart contract through the implementation of these updates.


If your Next.js server was offline, you can bring it back up by executing the command 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 House Rental Platform using Next.js, Redux, and Solidity. 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. You also learned how to use Redux for shared data space and interact with smart contracts from the frontend.


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

About Author

I am a web3 developer and the founder of Dapp Mentors, a company that helps businesses and individuals build and launch decentralized applications. I have over 7 years of experience in the software industry, and I am passionate about using blockchain technology to create new and innovative applications. I run a YouTube channel called Dapp Mentors where I share tutorials and tips on web3 development, and I regularly post articles online about the latest trends in the blockchain space.


Stay connected with us, join communities on Discord: Join X-Twitter: Follow LinkedIn: Connect GitHub: Explore Website: Visit