What you will be building, see the live demo at Bitfinity test network and the git repo.
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.
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.
Watch the following instructional videos to receive up to 3-months of free premium courses on Dapp Mentors Academy, including:
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.
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.
Our frontend is ready for smart contract integration, but we need to implement Redux to enable 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:
- Create a
store
folder at the project root. - Inside
store
, create two folders:actions
andstates
. - Inside
states
, create aglobalStates.js
file.
- Inside
actions
, create aglobalActions.js
file.
- Create a
globalSlices.js
file inside thestore
folder.
- Create an
index.js
file inside thestore
folder.
- 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:
- Create a
contracts
folder at the project root. - Inside
contracts
, create aDappBnb.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:
Contract Setup and Libraries: The contract imports
Ownable
,Counters
, andReentrancyGuard
from the OpenZeppelin library.Ownable
provides basic authorization control functions,Counters
is used for counting variables, andReentrancyGuard
helps prevent re-entrancy attacks.Struct Definitions: The contract defines three structs:
ApartmentStruct
,BookingStruct
, andReviewStruct
. These define the data structures for apartments, bookings, and reviews respectively.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.
Constructor: The constructor function initializes the
taxPercent
andsecurityFee
state variables.Apartment Functions: Functions like
createApartment
,updateApartment
,deleteApartment
,getApartments
, andgetApartment
are used to manage apartment listings on the platform.Booking Functions: Functions like
bookApartment
,checkInApartment
,claimFunds
,refundBooking
,getUnavailableDates
,getBookings
,getQualifiedReviewers
, andgetBooking
are used to manage the booking process and interactions between tenants and apartment owners.Review Functions: The
addReview
andgetReviews
functions manage the review process, allowing tenants to leave reviews for apartments they've booked.Utility Functions: The
payTo
andcurrentTime
functions are utility functions used in multiple other functions.payTo
is used to transfer funds between addresses, andcurrentTime
returns the current block timestamp.
Contract Deployment and Seeding
Now, let's deploy our smart contract and populate it with some dummy data:
- Create a
scripts
folder at the project root. - Inside
scripts
, create adeploy.js
and aseed.js
file and add the following codes.
Deploy Script
Seed Script
-
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.
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:
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.
getApartments, getApartment: These functions fetch all apartments and a specific apartment respectively from the smart contract.
getBookings: Fetches all bookings for a specific apartment from the smart contract.
getQualifiedReviewers: Fetches all addresses that are qualified to leave reviews for a specific apartment.
getReviews: Fetches all reviews for a specific apartment from the smart contract.
getBookedDates: Fetches all dates that are booked for a specific apartment from the smart contract.
getSecurityFee: Fetches the security fee from the smart contract.
createApartment, updateApartment, deleteApartment: These functions allow a user to create, update, and delete apartments respectively.
bookApartment: This function allows a user to book an apartment for specific dates.
checkInApartment: This function allows a user to check into an apartment.
refundBooking: This function allows a user to get a refund for a booking.
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 recommends watch the full video of this build on our YouTube channel and visiting our website for additional resources.
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
Top comments (1)
OMG. Worth reading indeed. Infact its an amazing idea. Especially with the evolution of AI a good developer can do wonders in this field. Going to share it at vacationrentallicense.com. Its one of my airbnb rental licensing service base website.