Introduction
Imagine the possibility of sending payments globally without the usual bureaucratic hassle and fees associated with traditional banking systems.
This has been made possible with the emergence of blockchain technology and cryptocurrencies.
Today, we focus on a platform that makes this possible and simple: Celo.
Celo is a mobile-first blockchain platform that aims to increase cryptocurrency adoption among smartphone users. By using phone numbers as public keys, Celo hopes to introduce the world’s billions of smartphone owners to the exciting world of blockchain.
This article will focus on building a front-end decentralized payment application using the Celo blockchain platform, leveraging React for the front end.
We will walk you through the steps, explaining every detail and providing code examples.
Pre-Requisites
Before we dive into the code, let’s first ensure we have everything we need. To follow along with this tutorial, you should have:
- Node.js installed (Version 12 or above)
- A basic understanding of React
- A basic understanding of Celo Blockchain and its SDK
- Celo extension wallet installed on your Chrome browser
Setting Up the Environment
To set up the development environment, we will initialize a new React project. You can use the ‘create-react-app’ command to achieve this. If you don’t have it installed, use the following npm command:
mkdir First-Celo-Smart-Contract
cd First-Celo-Smart-Contract
npm install -g create-react-app
Then, create a new React app:
create-react-app celo-dapp
Installing Dependencies
For our application, we will need several dependencies. Let’s install them:
npm install @celo/contractkit web3 dotenv
@celo/contractkit
is Celo’s SDK, which allows us to interact with the Celo blockchain.web3
is a collection of libraries that enable you to interact with a local or remote Ethereum node.dotenv
is a zero-dependency module that loads environment variables from a.env
file intoprocess.env
.
Connecting to the Celo Network
To interact with the Celo network, we need to set up a provider. We will create a helper file for this purpose. Let’s call it celo.js
:
import { newKit } from '@celo/contractkit'
let kit
const connectCeloWallet = async function () {
if (window.celo) {
try {
await window.celo.enable()
kit = newKit("https://alfajores-forno.celo-testnet.org");
} catch (error) {
console.log("Error connecting to Celo Wallet: ", error)
}
} else {
console.log("Please install the CeloExtensionWallet")
}
}
export { connectCeloWallet, kit }
In this code, we use the Celo Extension Wallet, which will inject a celo
object into our application’s window.
We can then use window.celo.enable()
to request permission to connect to the user’s Celo wallet. The newKit()
function allows us to create a new instance of the ContractKit, which is essential for interacting with the Celo network.
Building the User Interface
In the next step, we will create a simple form for users to make payments. The form will capture the recipient’s address and the amount to be transferred.
In your App.js
:
import React, { useState } from 'react';
import { connectCeloWallet, kit } from './celo';
function App() {
const
[recipientAddress, setRecipientAddress] = useState("");
const [amount, setAmount] = useState("");
const handleRecipientAddressChange = (event) => {
setRecipientAddress(event.target.value);
};
const handleAmountChange = (event) => {
setAmount(event.target.value);
};
const sendPayment = async () => {
// Payment logic goes here
}
return (
<div className="App">
<input
type="text"
placeholder="Recipient Address"
value={recipientAddress}
onChange={handleRecipientAddressChange}
/>
<input
type="number"
placeholder="Amount"
value={amount}
onChange={handleAmountChange}
/>
<button onClick={sendPayment}>
Send Payment
</button>
</div>
);
}
export default App;
Here we created two state variables, recipientAddress
and amount
.
We also created two functions to handle changes in the input fields and the sendPayment
function, which will be responsible for sending the payment.
Implementing the Payment Function
Finally, let’s implement the logic to send payments.
const sendPayment = async () => {
if (amount <= 0) {
console.log('Amount must be greater than zero')
return
}
try {
const amountInWei = kit.web3.utils.toWei(amount, 'ether')
const goldtoken = await kit.contracts.getGoldToken()
const tx = await goldtoken.transfer(recipientAddress, amountInWei).send({ from: kit.defaultAccount })
const receipt = await tx.waitReceipt()
console.log('Transaction receipt: ', receipt)
} catch (error) {
console.log('Payment failed: ', error)
}
}
Here, we first convert the amount from ether (the standard denomination used in the app) to wei (the smallest denomination on the Celo network).
Then, we create a transaction to transfer the specified amount to the recipient’s address. Finally, we wait for the transaction receipt, which indicates that the transaction was successful.
Conclusion
Building a decentralized payment application using Celo and React opens up a world of possibilities for facilitating peer-to-peer transactions.
By harnessing the potential of Celo’s blockchain technology, we can bypass traditional financial intermediaries, making the process faster, more secure, and accessible.
Nonetheless, this guide should give you a head start in developing dApps on the Celo platform.
Next Steps
Once you have the basic decentralized payment application set up, there are several enhancements and additions you could consider:
- Form Validation: Implement thorough validation for the payment form. For instance, you could check whether the recipient’s address is a valid Celo account.
- Integration with other Celo Tokens: Currently, we have only implemented the transfer of Celo’s native token (Celo Gold). You can expand this to include other tokens supported by Celo, such as Celo Dollar (cUSD).
- User Interface/Experience: Enhance the user interface and experience. Aesthetics and user experience play a vital role in any application, and dApps are no exception.
- Deploying the App: Finally, deploy your app so that others can access and use it. You can use platforms like Netlify, Vercel, or GitHub Pages for deploying your React application.
- Security Measures: Last but not least, always focus on security measures while dealing with blockchain applications. As you deal with sensitive data such as wallet addresses and transactions, it’s important to ensure top-notch security to avoid any exploits or hacks.
Remember, dApp development is a continuous process, and there’s always something to improve, enhance, or add.
About the Author
Aborode Prime Olusegun is a Growth Marketer and Data Analyst. He’s got a huge interest in Web3 and the decentralisation that it offers. Twitter