Revolutionizing Travel Planning: Building a Decentralized Travel Planning DApp with Celo

Revolutionizing Travel Planning: Building a Decentralized Travel Planning DApp with Celo https://celo.academy/uploads/default/optimized/2X/8/89db384fffe10e69a5b03d0ea77f179ba67435e1_2_1024x576.jpeg
none 0.0 0

Introduction:

Blockchain has come a long way revolutionizing various businesses, and industries and changing the way we transact in the digital world. It has evolved a great innovation potential.
Another significant advancement in blockchain technology is smart contracts. These contracts are self-executed and are encoed on the blockchain to eliminate the need for any intermediary and also provide a secure environment for the completion of agreements. DeFi (also known as decentralized finance) came up to open possibilities for financial inclusivity and providing access to traditional banking services.

Using the DeFi protocol, individuals can participate in borrowing, lending, trading, and exchanging without relying on centralized portals. It has made it more accessible and efficient.

Prerequisites:

  • You need to have a basic knowledge of smart contracts and Celo Network on blockchain.
  • You should be familiar with Solidity Programming Language and Remix IDE.

Building a DApp, or a Decentralized Application to revolutionize Travel Planning using Celo

We are building this DApp to revolutionize the way people plan their travel, as a decentralized platform aims to give a secure, efficient, and transparent ecosystem for travelers, agencies, and service providers too! Interesting right?

Those traditional travel platforms rely on centralized intermediaries whereas Travel Planning Dapp will harness the decentralized nature of the blockchain network which will eliminate the intermediaries, cut down the costs, trustful environment with huge control over users for their travel arrangements.

Features and benefits which the DApps will include are:

  1. Trustful experience: Travel Planning DApps will use Celo’s blockchain decentralized architecture, which will ensure that no single entity or person has control of the platform. This decentralized environment enables direct peer-to-peer interactions making it transparent and eliminating the need for intermediaries.
  2. Secured Transaction: By using Celo’s blockchain cryptographically secured environment, this travel planning Dapp will enable tamper-free transactions. Payments, any sensitive data, and bookings will be stored on the blockchain only which will reduce the risk of fraud and data breaches.
  3. Utilization of Smart Contracts with Celo: Self-executing agreements will be used on the DApp making it automated enforcing the terms and conditions and making it streamlining the process of booking confirmations, Payments, or refunds.
  4. Easy Payments and Remittances: cUSD is Celo’s native stablecoin which will facilitate seamless and fast transactions within the DApp where users can easily pay for their bookings or any services they wish to take paying through their Celo wallets. Using the Celo wallet the users will be able to cut down the transaction costs which will help them to make great travel arrangements at a great price.
  5. Tokenization: This Travel planning DApp can use Celo’s native asset such as CELO, or other tokens to reward the users for their engagement on the DApp. By using the DApp as a booking agent, or a user itself, they can earn tokens for activities on the DApp by writing reviews, Referring other people on the platform, etc. This will give a boost to the DApp making it popular in the community.

Getting Ready to Build: Setting Up the Development Environment

To get started with building your awesome Travel Planning DApp using Celo, it will require you to install Node.js and npm. It’s an easy and quick process to do that! Just follow the quick steps below:

  1. Installing the node.js environment on your system: You can download the Node.js from their official website i.e. nodejs.org by choosing the suitable version for your operating system whether you are using Windows or macOS, or any other OS.
  2. Running the Installer: After the download has been completed, click on Run the Installed and follow the steps to install node.js by accepting the license agreement and choosing the installation directory. Also, you can leave the default settings as they are because they don’t have much to do.
  3. Verifying the installation: After the installation has been completed, you need to open a command prompt window or a terminal window using Ctrl+R and type cmd on Windows or just open the terminal window from spotlight search in MacOS. After opening the window, write node -v, and npm-v to make sure they are installed successfully. It will show the version if they are properly installed.

It’s done quickly and easily, right? Now you have the node.js and npm installed on your system and you can proceed to the next steps.

Connecting To the Celo Network

Now the next step is to connect with the Celo Network.
It’s time to import the necessary dependencies into our travel planning project.

We’ll use the Alfa Jungle testnet to test our DApp and Celo JavaScript SDK which will provide a convenient set of utilities for connecting with the Celo Network. We can use Node packet manager (npm which we previously installed above) to install the required packages. Open the cmd or terminal on your system and go to the project directly, also you can simply open the project directory first and then open a command prompt there only.

After opening, run the following command: npm install @celo/contactkit

This command will install the Celo ContactKit package.

After installing the Celo ContractKit, we need to establish a connection to Celo’s Alfajungle Testnet. This testnet will allow us to simulate our code on the Celo blockchain environment for development purposes. We can do it in javascript using the following code below:

const Web3 = require(‘web3’);

const ContractKit = require('@celo/contractkit');

// Initialize a new web3 instance

const web3 = new Web3('https://alfajungle.celo-testnet.org');

// Initialize the ContractKit with the web3 instance

const kit = ContractKit.newKitFromWeb3(web3);

First, we are initializing the new web3 instance and then connecting it to Celo’s Alfajungle Testnet. After that, we initialized the ContractKit.

Creating an Account and Getting The Private Key

After initializing the ContractKit, we need to create an account on the Celo blockchain to interact with it. We can create a new account using the ContractKit itself and obtain a private key for signing the transactions. Here is the code below to do that :

async function generateAccount() {

const account = kit.web3.eth.accounts.create();

const privateKey = account.privateKey;

console.log('Account address:', account.address);

console.log('Private key:', privateKey);

}

generateAccount();

We are using ‘create()’ from ‘kit.web3.eth.accounts’ to create a new account and obtain a private key.

Interacting with the Celo Blockchain:

After getting our account set up and importing the necessary things, we need to interact with the Celo contacts in our travel planning DApp. The Celo JavaScript SDK will give convenient methods for interacting with the smart contracts on the Celo Network.

Setting up the Default Account:

We need to set up the default account before interacting with the contracts on Celo. We can set it up by using the ‘kit.defaultAccount’.

Use the code:

const accountAddress = ‘y_account_address>'; // Replace this with your actual account address

kit.defaultAccount = accountAddress;

Replace the y_account_address with the actual account address which you have generated.

We can also fetch the Account balance using the Celo JavaScript SDK using the below code:

async function fetchAccountBalance() {

const account = await kit.web3.eth.getAccounts();

const balance = await kit.getTotalBalance(account[0]);

console.log('Account balance:', balance.toString());

}

fetchAccountBalance();

We have used kit.web3.eth.getAccounts() to get the account linked with the default account and then send it to kit.getTotalBalance() to retrieve the total balance which includes CELO and cUSD.

Executing the Smart contract for Travel planning:

We have to implement a smart contract that can handle the functionalities of our application, for that we will use Remix IDE and Solidity Programming Language.

Writing a Solidity Smart Contract using the Remix IDE:

To do this, we need to open Remix IDE on our browser. It’s a web-based development environment for writing and testing our smart contracts, it is great as it does both.

We need to create a new file and name it whatever you want. Here I am naming it “TravelPlanningDApp.sol”

Defining the Structure of Booking:

In our smart contract, we need to define a structure or struct to show a booking. We will declare some necessary variables too to keep track of payments and bookings. Here’s the code for the struct:

pragma solidity ^0.8.0;

contract TravelPlanningDApp {

struct Booking {

uint256 id;

address traveler;

string destination;

uint256 amount;

bool paid;

bool canceled;

}

Booking[] public bookings;

uint256 public nextBookingId;

// Other necessary variables

}

We defined a struct known as ‘Booking’ in this code which basically represents a travel booking. It will contain ‘id’, ‘destination’, ‘traveler’, and the booking ‘amount’.

Implementing Functions for the Creation of Bookings, Cancelling the Bookings, and Making Payments:

We have to implement functions that will make the users create travel bookings, initiate payments and cancel the bookings. Here is the code to do the same:

function createBooking(string memory _destination, uint256 _amount) public {

Booking memory newBooking = Booking({

id: nextBookingId,

traveler: msg.sender,

destination: _destination,

amount: _amount,

paid: false,

canceled: false

});

bookings.push(newBooking);

nextBookingId++;

}

function makePayment(uint256 _bookingId) public payable {

require(_bookingId < bookings.length, "Invalid booking ID");

require(!bookings[_bookingId].paid, "Booking already paid");

Booking storage booking = bookings[_bookingId];

require(msg.sender == booking.traveler, "Only the traveler can make the payment");

booking.paid = true;

}

function cancelBooking(uint256 _bookingId) public {

require(_bookingId < bookings.length, "Invalid booking ID");

require(!bookings[_bookingId].canceled, "Booking already canceled");

Booking storage booking = bookings[_bookingId];

require(msg.sender == booking.traveler, "Only the traveler can cancel the booking");

booking.canceled = true;

}

You can also add some more functions if you want by using various codes.

Deploying the Smart Contract using the Remix IDE:

As we have successfully implemented the Smart Contract for our DApp, we will move on to the next step i.e. deploying it to the Celo Network making it accessible on the blockchain network.

To do this we’ll follow some simple steps:

  1. Connecting to The Celo blockchain: We have to connect the Remix IDE to the Celo Network and ensure that Deploy & Run Transactions” Tab is selected. On the right side pane, you’ll see the “Environment” menu, choose “Inject Web3” from there. This will inject the Celo Web3 into Remix.
  2. Selecting the Smart Contract: Open the solidity file .sol which contains the travel planning smart contract. Make sure that the correct contract is selected for the deployment.
  3. Configure the Parameters: We need to configure some parameters before deployment as our contract requires any constructor argument or something. You must set the appropriate values according to your contract.
  4. Deploy the Smart Contract: Once you have configured those, you can deploy the smart contract. Press the “Deploy” button on the IDE. The IDE will show ask you to confirm the transaction details which will include the gas fee. Confirm the transaction and wait for deployment.
  5. Interacting with the Deployed Smart Contract: You can interact with the deployed smart contract after the confirmation as Remix IDE will show you the address of the smart contract. You may use this address to interact with the deployed contact.

Integration of Smart Contract into DApp

We need to connect our Smart Contract with the DApp by the following code below:

const contractAddress = '<smart_contract_address>'; // Replace with your actual contract address

const contractABI = require('<contract_abi_file>'); // Replace with the path to your contract ABI file

const contract = new web3.eth.Contract(contractABI, contractAddress);

Now we can call functions using:

async function createBooking(travelerAddress, destination, travelDates) {

try {

const transaction = await contract.methods.createBooking(travelerAddress, destination, travelDates).send({ from: defaultAccount.address });

console.log('Booking created:', transaction.transactionHash);

} catch (error) {

console.error('Failed to create booking:', error);

}

}

Finally, we have integrated the functions and smart contract into our Travel Planning DApp.

We can add some more functions to our code as:

// Make a payment for a booking

async function makePayment(bookingId, amount) {

try {

const transaction = await contract.methods.makePayment(bookingId).send({ from: defaultAccount.address, value: amount });

console.log('Payment successful:', transaction.transactionHash);

} catch (error) {

console.error('Payment failed:', error);

}

}

// Cancel a booking

async function cancelBooking(bookingId) {

try {

const transaction = await contract.methods.cancelBooking(bookingId).send({ from: defaultAccount.address });

console.log('Booking canceled:', transaction.transactionHash);

} catch (error) {

console.error('Failed to cancel booking:', error);

}

}

// Example

const travelerAddress = '0x1234abcd'; // Replace with the traveler's address

const destination = 'London';

const travelDates = '2023-05-24 to 2023-05-29’;

const bookingId = 1;

const paymentAmount = web3.utils.toWei('5', 'ether');

// Create a booking

createBooking(travelerAddress, destination, travelDates);

// Make a payment for a booking

makePayment(bookingId, paymentAmount);

// Cancel a booking

cancelBooking(bookingId);

Conclusion:

After completing this tutorial, we’ll be able to make a Travel Planning DApp using Celo Network which will be decentralized, safe, and secure.

We started by installing the development environment by downloading the node.js and npm and then we connected to Celo’s AlfaJungle testnet to create an account and obtain a private key to connect with the Celo Network. After that, we set up a default account and fetch up the account balance using the Celo Javascript SDK which allows us to manage the funds within the application,

Finally, we have used the solidity language and deployed the smart contract using Remix IDE and integrated it in the DApp and we can create bookings, make payments and, cancel the bookings too. We have created the DApp using Celo integration to revolutionize the travel industry and make use of blockchain to make it transparent and secure. I hope you like this tutorial.

References

8 Likes

Thanks for such a great explaination.

2 Likes

@joenyzio @Celo_Academy

I will be rewiewing this.

1 Like

Congratulations on your first article, welcome to the community @dhruv

1 Like

I am unable to edit post @Celo_Academy

Can I know what issue are you facing while editing? @dhruv

I ain’t getting any option to edit which I was getting previously. It just shows edit history.

Can you attach the screenshot ? @dhruv


Congratulations on your first piece @dhruv

1 Like

I am able to see the edit icon, edit icon is the one with the pencil right next to your name above introduction left to 2d , I am able to see that in image 1, and would ask you to use a PC to make the edits, as it will be easier for you to make the changes @dhruv

@ishan.pathak2711 I tried that button it doesn’t open any editor.

Here is the Source Code Link as I am not able to edit the post : Source Code

Nice Work Dhruv Congratulations on your first piece.

2 Likes

Apologies for the issue here. Being new to the platform I hadn’t yet changed your permission level. I upgraded your permissions to member and gave you the Sage tag so that you can now create + edit posts. Congratulations on your first post!

1 Like

Great job on this article! Clear explanation and insights. Keep up the excellent work, I left some comments in your DM.