How to Build a Decentralized House Rental Platform with Next.js, Redux, and Solidity
Tags: web3, nextjs, solidity, dapp
Published: 2024-01-21 08:57:15

What you will be building, see the [live demo](https://dapp-bnb-x.vercel.app/) at Bitfinity test network and the [git repo](https://github.com/Daltonic/dappBnbX).

![House Rental Marketplace](https://github.com/Daltonic/dappBnbX/raw/main/screenshots/0.png)

![House Rental Marketplace](https://github.com/Daltonic/dappBnbX/raw/main/screenshots/1.png)

## 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](https://paper-attachments.dropboxusercontent.com/s_70534477D8955F3500A3FBCD4F334C4E7B1BEDE321CB5F5FC0792B12F0A26F99_1702985122073_tier.png)

## 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:


{% embed https://www.youtube.com/watch?v=qV1mbFOtkxo %}


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](https://forms.gle/uGtm3ZcEHb5pqd3YA).

Watch the following [**instructional videos**](https://www.youtube.com/playlist?list=PLUDcVqFK2t-C36KaTMzV3y1wu8Hf-qyAI) to receive up to 3-months of free premium courses on Dapp Mentors Academy, including:


- [Fullstack NFT Minting Course](https://dappmentors.org/courses/details/fullstack-nft-minting-course)
- [Fullstack NFT Marketplace Course](https://dappmentors.org/courses/details/fullstack-nft-marketplace-course)
- [Fullstack Blockchain Course](https://dappmentors.org/courses/details/fullstack-blockchain-101-course)
- etc.

Continue your Bitfinity journey by learning how to build easy Play-to-Earn dApps. Discover the potential of blockchain gaming in the next module. [**Dive deeper into Bitfinity and deploy your smart contracts to the network.**](https://bitfinity.network/)

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](https://dashboard.alchemy.com/) 
`WALLET_CONNECT_PROJECT_ID`: [Get Key Here](https://cloud.walletconnect.com/sign-in)

Finally, run `yarn dev` to start the project.


![Dummy Data](https://paper-attachments.dropboxusercontent.com/s_1ABC6310BD0B5901681AD464C42A11E11DD4768F3DF646D44647EADDF554A8D7_1703090776371_Screenshot+2023-12-20+at+5.46.07+PM.png)


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](https://paper-attachments.dropboxusercontent.com/s_1ABC6310BD0B5901681AD464C42A11E11DD4768F3DF646D44647EADDF554A8D7_1703240014742_Screenshot+2023-12-22+at+11.13.24+AM.png)


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.


{% gist https://gist.github.com/Daltonic/730e0819128d70d5881e00f5d8429e08 %}



4. Inside `actions`, create a `globalActions.js` file.


{% gist https://gist.github.com/Daltonic/fa755c554d2d4bcb3768f17b5075f976 %}



5. Create a `globalSlices.js` file inside the `store` folder.


{% gist https://gist.github.com/Daltonic/47f743789f5d7b075c193cddafcb948e %}



6. Create an `index.js` file inside the `store` folder.


{% gist https://gist.github.com/Daltonic/187fbf81056b88f2723da8b701f81ea2 %}



7. Update the `pages/_app.jsx` file with the Redux provider.


{% gist https://gist.github.com/Daltonic/9c242246cfaa297a1b1bb6c90ac4457a %}


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.


{% gist https://gist.github.com/Daltonic/ba8ddb07089839d2d8219b15a2f97787 %}


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**

{% gist https://gist.github.com/Daltonic/33dd48c1b599610d7fa5e81e838ae9d7 %}


**Seed Script**

{% gist https://gist.github.com/Daltonic/5b258259081ddcf8d0b8ce5f6960e7bf %}



3. 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](https://paper-attachments.dropboxusercontent.com/s_70534477D8955F3500A3FBCD4F334C4E7B1BEDE321CB5F5FC0792B12F0A26F99_1702992266380_Screenshot+2023-12-18+at+10.01.28+AM.png)


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


{% embed https://www.youtube.com/watch?v=Ubom39y5jX8 %}



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


{% gist https://gist.github.com/Daltonic/b6fc5166eb220378d79f854f125ce804 %}


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.


{% gist https://gist.github.com/Daltonic/a811673bd1fe4b0c0011ae1b3b59af0d %}



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


{% gist https://gist.github.com/Daltonic/e9f1338669629696eb0502dc75331c25 %}


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


{% gist https://gist.github.com/Daltonic/644a31568918fbf7d2d7149ae89124db %}


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


{% gist https://gist.github.com/Daltonic/6435864d609e010ec5e8cc775254cdf3 %}


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


{% gist https://gist.github.com/Daltonic/f231fadbce1d6f58ab53eef044311f33 %}


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


{% gist https://gist.github.com/Daltonic/c4bae4f5f8be07dc1509d7a3cd8623de %}



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


{% gist https://gist.github.com/Daltonic/b66fcb35c423e2795c1328388f6870bc %}


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


{% gist https://gist.github.com/Daltonic/6901c666280934c5e9b8b6c145d449f5 %}


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. 


{% gist https://gist.github.com/Daltonic/4042c750d7a8741af607aabaebbfd3fd %}


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


{% gist https://gist.github.com/Daltonic/438126facc462f32cc78d4b5a3514413 %}


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 recommends watch the full video of this build on our [**YouTube channel**](https://www.youtube.com/@dappmentors?sub_confirmation=1) and [**visiting our website for additional resources**](https://dappmentors.org/).


{% embed https://www.youtube.com/watch?v=Qoa6z6c_wYQ %}



## 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](https://dappmentors.org/), 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**](https://www.youtube.com/@dappmentors?sub_confirmation=1) 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](https://discord.gg/PgFDUVT6n9)
X-Twitter: [Follow](https://twitter.com/iDaltonic)
LinkedIn: [Connect](https://www.linkedin.com/company/dapp-mentors)
GitHub: [Explore](https://github.com/Daltonic)
Website: [Visit](https://dappmentors.org/)