Skip to main content

6 posts tagged with "composer"

View All Tags

· 11 min read
Ernest Nnamdi

header

Hello there!! 🙋🏾‍♂️

This is the third instalment of the composer series where I demonstrate how to build defi applications in no time using the Celo-composer. The first two instalments were Building a crowdfunding refi dapp using celo composer and react and Building a decentralized newsfeed with Celo composer, React, and IPFS.

The Radical Shift

So here I’m thinking that every company, tech or otherwise will eventually come to be functionally web3-savvy to various degrees. Ultimately, if they play in these climes for long enough.

We have more companies globally, waking up to the fact they can do more with blockchain technology. This means, of course, they are probably already sighing at the tedium that comes with migrating to or incorporating web3 into their existing systems.

Blockchain companies are now burdened with the task of juggling both providing vital services and lowering the learning curve. At the critical merge point ( the point where new tech is introduced into the work dynamic), plan-to-execution time drops significantly ( this is precipitated by the need to work in a different way that requires the usage of the particular tech i.e web3 in this instance).

The obvious solution then becomes creating solutions that ease developers into web3. This my friends is where Celo stands clear of the crowd. In what regard you may ask? The success of web3 and the full potential of blockchain technology can only be realised with massive adoption. Without adoption, there will be no reason to build. That’s why Celo has taken the lead in the industry by providing tooling to support developers of all levels, from the expert to the web2 developer still toying with the idea of building defi applications. One of such tools is the Celo composer.


Celo Composer

The Celo Composer is a starter pack built on the react-celo toolkit to get you up and running fast in developing DApps on the Celo blockchain. This starter pack is best suited for web2 developers currently transitioning into web3 as it abstracts all the complexities involved in setting up and developing Defi applications and replaces them with a plug-and-play environment.

The starter pack, which currently supports React, React-Native, and Flutter requires little to no configurations from you as it eases you into the web3 sphere.

Now for today’s project

Here’s a list of what we’ll cover in this article:

  • ✅ Step 1: Setting up your environment.
  • ✅ Step 2: Creating your smart contract.
  • ✅ Step 3: Deploying your smart contract.
  • ✅ Step 4: Getting started with the frontend.
  • ✅ Step 5: Interacting with your smart contract from the frontend.

What are we building?

In this article, we are going to use the Celo Composer starter-kit which comes pre-integrated with NextJS, and also Tailwind for styling. This dapp will allow users whose wallet are connected, stake their tokens and earn returns on them.

full-build

This is the end result of our project today. If your learning style is “code first”, you can find the complete code for this project here on Github.

Do follow the commands in the README-md file to get started with setting up your project.

Prerequisites

  • Solidity
  • React
  • Tailwind

Step 1: Setting up your environment ✅​

There are two options to setting up your environment.

Using the Template:

Navigate to the Celo Composer repository and follow the step by step guide entailed in the README-md.

celo-composer

Using the CLI:

The Celo Composer CLI is the easiest way to setup your environment because unlike the first option, it only installs dependencies and boilerplate code necessary for the framework you intend to use.

npx @celo/celo-composer create

Running this command throws up a prompt for you to select the framework of your choice and you are fully setup to start using the starter-kit.

To install dependencies locally and setup test wallet, please refer to the README-md.

Step 2: Creating your smart contract ✅

  • Open your project on your text editor and ensure you’re on the root folder and the navigate to the packages/hardhat folder and rename the .envexample file to .env.

  • In the .env file, paste in the private key of your wallet. If you are wondering where to find your private key, please refer to the README-md in the Celo composer repository. If you prefer to setup your metamask wallet to work with this and future projects, please refer to this guide.

code

  • Navigate to the contracts folder and here we are going to add two contracts. One for the ERC20 token we are going to be using, and our staking contract. So create two new files, Piron.sol and Staking.sol respectively.

code

  • In the Piron.sol file, paste in this contract and save. This is a basic ERC20 contract compliant with the IERC20 standards. This token whose symbol is PTK will serve as our staking and reward token.

code

  • In the Staking.sol file, paste in this contract. This is a simple staking contract that accepts the address of our token(Piron token) and assigns it to the pirToken variable. This contract has six functions or methods but we will only be interacting with three, which are the staking function, pause and unpause function.

code

Step 3: Deploying your smart contract ✅

After setting up and creating our smart contracts, the only thing left to do on the backend of our project is to deploy it to the blockchain. Deploying contracts using the Celo Composer toolkit is an unbelievably seamless process.

  • Navigate to the deploy folder in the hardhat directory and in your 00-deploy.js file, you will see the deployment function for the greeter contract(A sample contract that comes with the starter kit).
await deploy(“Greeter”, {
from: deployer,
args: [“hello world”],
log: true,
})

Update the function to deploy your PironToken and StakePIR by replacing the function with this

const piron = await deploy(“PironToken”, {
from: deployer,
log: true,
})

await deploy(“Greeter”, {
from: deployer,
args: [piron.address],
log: true,
})

module.exports.tags=["PironToken", "StakePIR"];

code

We have two deploy functions, the first functions (piron) deploys our staking and reward token and the second deploys our staking contract and takes as an argument, the contract address of our token(PironToken).

There you have it! All that is left to do, is to open up your terminal, navigate to the hardhat directory

cd packages/hardhat

and run

yarn deploy

This compiles your contracts and deploys them to the Celo blockchain (Alfajores testnet).

View smart contract

Open the Celo Block Explorer (Alfajores Testnet) and paste the transaction or deployed address to view the transaction or smart contract. You can also check your wallet to confirm that the gas fee has been deducted from your balance.


Step 4: Getting started on the frontend ✅

Now we are done with the hardhat folder, we move on to the react-app folder. Navigate to the react-app folder by running on your terminal

cd ../react-app

or if you are in the root directory

cd packages/react-app

Tailwind

Follow the official tailwind guide to add tailwind to your project.

Note: Ensure you are in the react-app directory before installing tailwind.

After installing tailwind, you will notice two new files has been created for you. In the tailwind.config.js file, replace the boilerplate code with this.

code

After updating the tailwind config file, create a new folder in the react-app directory called styles.

In this new folder, create a file called global.css and then paste in this code. These are just basic styling and mostly gradients(most of which we are not going to use, so feel free to take advantage of them to customize your frontend).

code

The final setup for the tailwind configuration is to import the global.css file in the pages/_app.tsx file.

 import “../styles/global.css”;

Add this below the import statements in your _app.tsx file and voila we are done setting up tailwind.

code

AppLayout.tsx

The first file we are going to change is the components/layout/AppLayout.tsx file. We are going to replace it with the following code:

import * as React from “react”;
import Meta from “../meta/Meta”;
import { Header } from “./Header”;
interface Props {
title: string;
description: string;
children: React.ReactNode;
}
export default function AppLayout({ title, description, children }: Props) {
return (

<div className=”flex-1 h-full bg-gray-800">
<Header />
<Meta title={title} description={description} />
{children}
</div>
);
}

code

Utils/Index.tsx

In the utils folder, you are going to add one more utility function to the index.tsx file. Paste in this function below

export function formatTime(timestamp: number) {
const milliseconds = timestamp \* 1000;
const dateObject = new Date(milliseconds);
const humanDateFormat = dateObject.toLocaleDateString()
return humanDateFormat;
}

Step 5: Interacting with your smart contract from the frontend ✅

Index.tsx

Next file we are going to work on, is the index.tsx file. Here, we are going to delete all the placeholder code and replace it with this

code

Code Walkthrough
const contracts =
deployedContracts[network?.chainId?.toString()]?.[
network?.name?.toLocaleLowerCase()
]?.contracts;

The variable contracts is being assigned, every deployed contract which is imported from the deployments folder in the hardhat directory. The variable is in turn, being passed in to the HomePage.tsx.

HomePage.tsx

Navigate to the pages directory and create a new file called HomePage.tsx and in this newly created file, paste in this code. This will serve as as our home screen.

code

Code walkthrough
const { kit, address } = useCelo();

The useCelo() is gotten from react-celo which is a React hook and the easiest way to access Celo in your React application. Kit is used to query onchain data while address returns the address of the user after the connect function has connected the wallet to the project(Refer to components/layout/Header.tsx to see the connect function in action).

const pironContract = contracts
? (new kit.connection.web3.eth.Contract(
contracts.PironToken.abi,
contracts.PironToken.address
) as any as PironToken)
: null;

This creates a new instance of the contract (In this case our PironToken contract). It leverages kit which was destructured from useCelo() to create a new contract instance by passing in, the abi and address of the contract.

Note: “contracts” was passed in to the HomePage from the Index.tsx and contains all deployed contracts if any.

await pironContract.methods
.approve(contracts.StakePIR.address, “1000000000”)
.send({ from: address });

The above function is contained in the submit function and it is responsible for calling our smart contract methods or functions. This particular function calls the approve function in the pironContract and passes as arguments, the contract address of the staking contract and also a gas amount.

const paused = await stakingContract.methods.paused().call();

The above function, is quite similar to the previous in the sense that they both call methods or functions in the smart contract but do notice that theres is a difference between them. .call() is used in place of .send({…}) this is because this particular function does not create a new transaction on the blockchain.

Input.tsx

Navigate to the components directory and create a file called Input.tsx and paste in this code. This component is our custom input field to accept input from the frontend.

code

ProjectCard.tsx

Still in the components directory, create another file called ProjectCard.tsx and paste this code in it. The ProjectCard component is a way to display all the data we fetch from the blockchain.

This card will contain relevant information about our stake contract like number of stakers, start date, end date, etc and also allow up to make some contract calls such as pause, unPause and Claim Rewards.

code

Conclusion

This brings to an end, this session on building with Celo composer. But your learning don’t have to end here as PRs are welcome for those who want to contribute to this project.

Here is a quick recap of everything we covered.

  • ✅ Step 1: Setting up your environment.
  • ✅ Step 2: Creating your smart contract.
  • ✅ Step 3: Deploying your smart contract.
  • ✅ Step 4: Getting started on the frontend.
  • ✅ Step 5: Interacting with your smart contract from the frontend.

For those who have questions or want to be part of our developer community, join us on discord!.

Till next time,

Adios ✌🏾

· 13 min read
Ernest Nnamdi

Hello, friends! 🙋🏾‍♂️

header

Stacks

What is the conventional wisdom for getting involved in web3? Something involving solidity.

What does this look like for you as a web2 developer seeking to make this transition? New language? - definitely, but also a headache of new tools and frameworks to learn and getting conversant with. The learning curve between you and your excellent Defi app causes light (or heavy) showers on your parade.

As a developer evangelist, I won't be doing my job if I didn't tell you there is a better way out. The blockchain space is still very much in the "developer phase," and companies, protocols, and blockchains now have the responsibility of lowering the barrier to entry by making it easy to break into blockchain from traditional web/mobile development.

This is an area where Celo stands clear of other blockchains and protocols with its impeccable SDKs, APIs, and toolkits. Speaking of toolkits, we will use the Celo Composer toolkit today.


Celo Composer

The Celo Composer is a starter pack built on the react-celo toolkit to get you up and running fast in developing DApps on the Celo blockchain.

This starter pack is best suited for web2 developers currently transitioning into web3 as it abstracts all the complexities involved in setting up and developing Defi applications and replaces it with a plug-and-play environment.

The starter pack, which currently supports React, React-Native, and Flutter requires little to no configurations from you as it eases you into the web3 sphere.

Now to the crux of the matter

Here's a list of what we'll cover in this article:

  • ✅ Step 1: Setting up your environment.
  • ✅ Step 2: Creating your smart contract.
  • ✅ Step 3: Deploying your smart contract.
  • ✅ Step 4: Getting started with the frontend.
  • ✅ Step 5: Interacting with your smart contract from the frontend.

What are we building?

In this article, we are using the Celo Composer starter-kit, which comes pre-integrated with NextJs, Tailwind CSS, and IPFS HTTP client, to build a decentralized news feed where users can connect their wallets and share news as it happens around them and also read submissions from others.

full-build

This is what the final project looks like. If your learning style is "head first," then you can find the complete code for this project on Github.

Do follow the commands in the README-md file to get started with setting up your project.

Prerequisites

  • Solidity
  • React
  • Tailwind

Setting up your environment

There are two options to setting up your environment.

Using the Template: Navigate to the Celo Composer repository and follow the step by step guide entailed in the README-md .

celo-composer

Using the CLI: The Celo Composer CLI is the easiest way to setup your environment because unlike the first option, it only installs dependencies and boilerplate code necessary for the framework you intend to use.

npx @celo/celo-composer create

Running this command throws up a prompt for you to select the framework of your choice and youre fully setup to start using the starter-kit.

celo-composer

To install dependencies locally and setup test wallet, please refer to the README-md.


Step 1: Create your smart contract ✅

  • On your terminal, make sure you are in the root directory and then navigate to the contracts folder by running the following command:
cd packages/hardhat/contracts
  • Create a new file in the contracts folder called NewsFeed.sol
  • Copy the smart contract code from here and paste it into the file you created, and now your NewsFeed.sol file should look like this:

newsfeed.sol


Step 2: Write your deploy script ✅

After setting up our environment and saving our smart contract in our newly created file, the next step is to update the deploy script to be able to compile and deploy our smart contract to the blockchain.

  • Navigate to the packages/hardhat/deploy/00-deploy.js file, and you'll see the deploy function for the greeter contract( A sample contract that comes with the starter kit).
await deploy("Greeter", {
from: deployer,
args: ["hello world"],
log: true,
})
  • Update the function to deploy our NewsFeed instead by replacing the function with this.
await deploy("NewsFeed", {
from: deployer,
log: true,
})
  • Once that is done, scroll to the bottom of the page and update the exports by adding NewsFeed to them, and voila, you are done! This is all the setup that is required on the backend.
module.exports.tags = ["NewsFeed"];

Step 3: Deploy your smart contract ✅

Now we are done with the smart contract and have updated our deploy script; next is deploying the smart contract to the blockchain. To do this, run a straightforward command. Go back to your terminal, ensure you're on the correct directory, i.e., packages/hardhat, then run

yarn deploy

View smart contract

Open Celo Block Explorer (Alfajores Testnet) and paste the transaction or deployed address to view the transaction or smart contract. You can also check your wallet to confirm that the gas fee has been deducted from your balance.


Step 4: Getting Started on the frontend ✅

Navigate to the React app by running the following command on your terminal.

Note: No worries if you have closed the terminal you used in deploying your smart contract! Ensure you are in the root directory of your application, then run the following

cd packages/react-app

If not, run the following

cd ../react-app

Note: This presumes you followed the env setup guide and have installed the dependencies already

Tailwind CSS

Follow the official tailwind guide to add tailwind to your project.

After that, delete everything in the tailwind.config.css file generated automatically for you and replace it with this code.

Your tailwind.config.js file should look like this now.

tailwind

Create a new folder called styles in your react-app directory and a new file in the styles folder called global.css. Paste this code into the global.css file.

Your global.css file should now look like this:

tailwind

The final setup for our tailwind configuration is to import the global.css file into the pages/_app.tsx file. Add

 import ../styles/global.css

to the list of imports, and voila! You are ready to start using tailwind in your project.

The next stop is the pages/index.tsx file. Delete everything in the file and replace it with this code. Your index.tsxfile should look like this:

index.tsx


AppLayout.tsx

Now, navigate to the layout/AppLayout which is nested in the components folder and update the function with the code below:

import * as React from "react";
import Meta from "../meta/Meta";
import Footer from "./Footer";
import Header from "./Header";
import { ToastContainer } from "react-toastify";

interface Props {
title: string;
description: string;
children: React.ReactNode;
}

export default function AppLayout({ title, description, children }: Props) {
return (
<div className="bg-gray-200 flex-1 h-full">
<Header ToastContainer={ToastContainer} />
<Meta title={title} description={description} />
{children}
<Footer />
</div>
);
}

AppLayout.tsx

Header.tsx

Still in the layout folder, Navigate to the layout/Header.tsx file and replace the existing code with this.

header.tsx

Footer.tsx

Same for the layout/Footer.tsx file. Replace the existing code with this:

import * as React from "react";
import { Link } from "@mui/material";
import Github from "@/public/Github";
import Discord from "@/public/Discord";

export default function Footer() {
const githubLink = "https://github.com/celo-org/celo-composer";
const discordLink = "https://discord.gg/cGCE9p9352";

return (
<footer className="flex flex-col items-center justify-center mt-20">
<h3 className="font-medium">Powered by Celo Composer</h3>
<div className="flex">
<Link href={githubLink} target="_blank">
<Github style={{ width: "40px", margin: "5px" }} />
</Link>
<Link href={discordLink} target="_blank">
<Discord style={{ width: "40px", margin: "5px" }} />
</Link>
</div>
</footer>
);
}

FeedList.tsx

Navigate to the react-app/components folder and create a new file called FeedList.tsx. In your newly created file, paste this code into it. Your FeedList.tsx file should now look like this.

FeedList.tsx

Feed.tsx

Still in the components folder, create another file called Feed.tsx. In this new file, paste the following code into it.

Feed.tsx

This concludes everything we have to do in the components folder.


Step 5: Interacting with your smart contract from the frontend  ✅

HomePage.tsx

Navigate to react-app/pages directory, and create a new file called HomePage.tsx. Please copy the code from here and paste it into your newly created file.

HomePage.tsx

HomePage

Code walkthrough

  const { kit } = useCelo();

The kit function, which allows you to create a new contract instance, is obtained from the useCelo() function. This function is part of the react-celo hook, formerly called use-contractkit. This manages access to Celo with a built-in headless modal system to connect to your users' wallet of choice. You can explore the react-celo hook further here.

const contract = contractData
? (new kit.connection.web3.eth.Contract(
contractData.abi,
contractData.address
) as any as NewsFeed)
: null;

This function creates a new instance of the contract by leveraging the kit function and passing as arguments, the abi and address which is contained in the contractData prop. This prop is being passed onto your HomePage from the Index.tsx file.

const getFeeds = async () => {
try {
setLoading(true);
const AllFeeds = await contract.methods.getAllFeeds().call();
/*
* We only need title, category, coverImageHash, and author
* pick those out
*/
const formattedFeed = AllFeeds.map((feed: any) => {
return {
id: feed.id,
title: feed.title,
category: feed.category,
coverImageHash: feed.coverImageHash,
author: feed.author,
date: new Date(feed.date * 1000),
};
});

setFeeds(formattedFeed);
setLoading(false);
} catch (err) {
error(`${err.message}`);
}
};

The getFeeds function, as the name implies, fetches all available feeds by querying the contract using the "contract" instance we created earlier. Contract.methods is how we access the functions or methods declared in the smart contract. getAllFeeds() is a function in the contract NewsFeed.sol. The rest of the code is basic javascript.


FeedPage.tsx

Please create a new file in the public directory called FeedPage.tsx and paste the following code into it.

FeedPage.tsx

FeedPage

This image is what the Feed page looks like after the feeds have been created.

Code walkthrough

const contractDataS =
deployedContracts[network?.chainId?.toString()]?.[
network?.name?.toLocaleLowerCase()
]?.contracts;

This is a similar function to the one in the index.tsx file. It returns all deployed contracts.

 const contractData = contractDataS.NewsFeed;

Here we select the particular deployment we want which is the NewsFeed contract we deployed at the beginning and assign it to a constant called contractData.

const contract = contractData
? (new kit.connection.web3.eth.Contract(
contractData.abi,
contractData.address
) as any as NewsFeed)
: null;

This function, the same as on the home page, creates an instance of the contract.

const getFeed = async () => {
try {
let feedId = getUrlValue()["id"];
const allFeed = await contract.methods.getAllFeeds().call();
const singleFeed: any = allFeed.filter((feed: any) => feed.id === feedId);

// Format feed
const formattedFeed = {
id: singleFeed[0].id,
title: singleFeed[0].title,
description: singleFeed[0].description,
location: singleFeed[0].location,
category: singleFeed[0].category,
coverImageHash: singleFeed[0].coverImageHash,
date: singleFeed[0].date,
author: singleFeed[0].author,
};

setFeed(formattedFeed);
} catch (error) {
console.log(error);
}
};

This function gets all the feeds and filters the result to return the feed whose id matches the id passed in.

The getRelatedFeeds() is quite similar to the getFeed() function. The difference being it takes the getFeed function a little further and filters the results based on categories.


UploadPage.tsx

In the pages directory, create one more file called UploadPage.tsx and paste the following code into it.

UploadPage.tsx

Code walkthrough

const client = create("https://ipfs.infura.io:5001/api/v0");

The above function creates an IPFS node and assigns it to a constant called client.

const uploadCoverImage = async (coverImage: ImportCandidate) => {
defaultToast("Uploading Cover Image...");

try {
const image = await client.add(coverImage);
await saveFeed(image.path);
} catch (err) {
error("Error Uploading Cover Image");
}
};

The uploadCoverImage function nested in the handleSubmit() function, takes in the image uploaded by the user and uploads it to IPFS. Then it calls the saveFeed() function while passing in the path to the image.

 const saveFeed = async (coverImage: string) => {
defaultToast("Saving Feed...");
console.log(title, description, category, location, coverImage);

try {
const UploadedDate = String(new Date());
console.log("contract", contract);
const gasPriceMinimumContract = await kit.contracts.connection.gasPrice();
await contract.methods
.createFeed(
title,
description,
location,
category,
coverImage,
UploadedDate
)
.send({ from: address, gasPrice: gasPriceMinimumContract });

success("Feed Saved Successfully");

// reset form
setTitle("");
setDescription("");
setCategory("");
setLocation("");
setCoverImage("");

// Redirect to Home Page
window.location.href = "/";
} catch (err) {
console.log(err);
error("Error Saving Feed");
}
};

The saveFeed function takes the path to the image from the earlier function.

 const gasPriceMinimumContract = await kit.contracts.connection.gasPrice();

This particular code block is for gas price estimation. It describes the amount of gas to be used for the transaction. The following block of code uses contract.methods to access the createFeed function declared in the NewsFeed.sol contract.

When adding information to the blockchain, we use the send() function (Recall in earlier contract interactions, we use call() function ), and it accepts two arguments, from and gasPrice. We pass the address of the user calling the contract obtained from the useCelo() function and the gasPriceMinimumContract as values for the arguments.

This function, when called, creates a new NewsFeed entry and saves it on the blockchain.

HomePage

HomePage


Congratulations

This brings to a fruitful end today's topic on building a decentralized news feed using Celo Composer and IPFS. You can review the checklist below and confirm that you have learned each.

Here is a quick recap of everything we covered.

  • ✅ Step 1: Setting up your environment.
  • ✅ Step 2: Creating your smart contract.
  • ✅ Step 3: Deploying your smart contract.
  • ✅ Step 4: Getting started on the frontend.
  • ✅ Step 5: Interacting with your smart contract from the frontend.

Challenge

Once more, I have left some homework for you to get your hands dirty. Refer to the FeedPage.tsx file. Now in the getFeed() function, focus on the line below:

  const allFeeds = await contract.methods.getAllFeeds().call();
const singleFeed: any = allFeeds.filter( (feed: any) => feed.id === feedId );

A better way to handle this would be to use the contract.methods function to call the getFeed() function in the NewsFeed.sol contract while passing in feedId as a parameter.

  • Repeat the same for the getRelatedFeeds() function

Share your results or questions on the discord channel (Please ask all questions in the Celo composer channel for visibility).

Till next time,

Adios !! ✌🏾

Check this project out on Github. Design Inspiration Olanetsoft

· 6 min read
Viral Sangani

Celo Composer now supports Flutter 🎉. Quickly develop mobile apps on Celo

header

Introduction

Celo Composer — Flutter is a kit where you can find all the code needed to kickstart and build the production-ready mobile dApp. It includes state management, wallet connect, great UI, and some standard UI widgets.

In this article, we will go through the Flutter version of Celo Composer, where we will learn how to connect your mobile app with crypto wallets and how to interact with Celo blockchain using Flutter.

· 9 min read
Ernest Nnamdi

How to quickly create and deploy a full-stack crowdfunding dApp on Celo.


header

Gm. 😎

A quick primer on ReFi

Even the mildly curious amongst you must have had an earful about ReFi. What is ReFi you might wonder?

It means Regenerative Finance, which is shifting the economy by transferring control of capital to communities most affected by racial, economic, and environmental injustices.

Celo's commitment to building financial systems with the objective to regenerate our planet is evident, even with its launch date as Celo Mainet was launched on Earth day. This commitment is what gave birth to the Celo climate collective. A brilliant example of a platform in tune with Celo ReFi objectives is Kickstarter.

It is a platform where creatives and organisations that would have otherwise been bereft of funding, raise funds to bring their objectives and goals to life. It is on this premise that we decided that the best first project for the Celo Composer should be a crowdfunding application.

Celo Composer:

This is a toolkit created by Celo to help abstract away the complexities involved in setting up a development and deployment environment for building deFi applications.

This toolkit is fully set up to run on the Celo blockchain and requires little to no configurations from you. Currently, the toolkit supports React, Angular, React-Native and Flutter.

Well well, away from the formalities and straight to the crux of the matter.

Here's a list of what we'll cover:

  • ✅ Step 1: Setting up your environment.
  • ✅ Step 2: Create your smart contract.
  • ✅ Step 3: Deploy your smart contract.
  • ✅ Step 4: Getting started on the frontend.
  • ✅ Step 5: Interact with your smart contract from the frontend.
  • ✅ Step 6: Deploy your DeFi application.

By the end of this article, you'll be able to create, deploy and interact with crowdfunding smart contracts on Celo's ultralight blockchain.


What are we building?

In this article, we are building a crowdfunding DeFi application. This is in line with Celo Foundation's commitment to reversing the effects of climate change on our environment using web3 technology. You can read more about Celo's Climate Collective here.

complete-image

complete-image2

You can find the complete project on Github, follow the commands in the README.md file.

Let's get building!


Prerequisites

  • Celo
  • React
  • Solidity

Setting up your environment:

Navigate to the project repo and select Use this template.

complete-image2

Refer to this comprehensive guide on setting up your Celo Composer development environment. From there you can quickly build, iterate and deploy new dApps on the Celo blockchain.


Step 1: Create your smart contract

  • Navigate to packages/hardhat/contracts/ and create a new file called CrowdFund.sol.

  • Copy the code here and paste it into the CrowdFund.sol file

crowd-fund

Your CrowdFund.sol file should now look like this.

Create another file in your contracts folder called Project.sol.

packages/hardhat/contracts

Copy the code here and paste it in your Project.sol file, and now your file should look like this.

project


Step 2: Write your deploy script

Now that your smart contract is complete, you'll update the deploy script. This will enable you to deploy this smart contract to the Celo blockchain.

Open the file packages/hardhat/deploy/00-deploy.js. Copy the deploy function below and paste it into the file.

await deploy("CrowdFund", {
from: deployer,
//args: [ "Hello", ethers.utils.parseEther("1.5") ],
log: true,
});

Ensure your CrowdFund deployment function looks like this:

project

Scroll to the bottom of your 00-deploy.js file and add your deployment to the module export tags.

module.exports.tags = ["CrowdFund"];

Step 3: Deploy your smart contract

Now you are done with the smart contract and it's time to deploy it. You can deploy your smart contract and it will be visible on the Celo block explorer

Open your terminal and run yarn deploy from within the packages/hardhatfolder.

yarn deploy

View smart contract

Open Celo Block Explorer (Alfajores Testnet) and paste the transaction or deployed address if you would like to view the transaction or smart contract. You can also check your wallet to confirm that the gas fee has been deducted from your balance.


Step 4: Getting started on the front-end

Navigate to the React app by running the following command on your terminal.

cd ../react-app

Adding tailwind css

Follow the official tailwind guide to add tailwind to your project. After that, delete everything in the tailwind.config.css file that was generated automatically for you and replace it with this code.

tailwind

Create a new folder called styles in your react-app directory, and also create a new file in the styles folder called global.css. Paste this code into the global.css file.

Your global.css file should now look like this:

global-css

  • The final setup for our tailwind configuration is to import the global.css file into the pages/\_app.tsx file.

  • Simply add import ../styles/global.css to the list of imports and voila! you are ready to start using tailwind in your project.

  • Next stop, is the pages/index.tsx file. Delete everything in the file and paste it in this code. Your index.tsx file should look like this:

Now, navigate to the layout/AppLayout which is nested in the components folder and update the function with the code below.

<div className="min-h-screen gradient-bg-welcome">
<Header />
<Meta title={title} description={description} />
{children}
</div>

applayout

The above should be what your AppLayout.tsx file will look like. Similarly, for the layout/Header.tsxfile, delete everything and paste in this code. Your Header.tsxcomponent should now look like this.

applayout

Back in the react-app/components folder, create three new files. Input.tsx, ProjectCard.tsx and Welcome.tsx. Populate these files by copying their respective codes from here.

Welcome.tsx

Your Welcome.tsx file should look like this.

applayout


Code Walkthrough:

Contract Instance
const contract = contractData
? (new kit.connection.web3.eth.Contract(
contractData.abi,
contractData.address
) as any as CrowdFund)
: null;

This method connects your React app to the smart contract you deployed earlier. It accepts two arguments which are the contractData.abi and the contractData.address. kit comes from the useCelo() which is gotten from the Celo composer toolkit. contractData is passed onto the Welcome.tsx component as a prop from the pages/Index.tsx component.

For reference, this is the function that creates the property contractData in pages/Index.tsx

const contracts =
deployedContracts[network?.chainId?.toString()]?.[
network?.name?.toLocaleLowerCase()
]?.contracts;

deployedContracts is derived from the import statement:

import deployedContracts from "@celo-composer/hardhat/deployments/hardhat_contracts.json";

This fetches all deployed contracts from the packages/hardhat/deployments folder.

Contract Interaction

const createProject = async () => {
const stableTokenAddress = await kit.registry.addressFor(CeloContract.StableToken)
const gasPriceMinimumContract = await kit.contracts.connection.gasPrice()
const {title, desc, img, duration, goal } = formData;
await contract.methods.startProject(stableTokenAddress, title, desc, img, duration, goal).send({from: address, gasPrice: gasPriceMinimumContract})
}

This functions interacts with your smart contract by calling it methods, which are functions declared in your smart contract. kit and address are obtained from the useCelo() function and makes easy, the task of getting your stableTokenAddress, gasPriceand your address. Your address is gotten when you login with your metamask wallet. This is done in the components/layout/Header.tsx component.

For reference, this is the code block that fetches your wallet address and logs you into the application.

{!address ? (
<button onClick={() => connect().catch(e => console.log(e))} className='bg-[#2952e3] py-2 px-7 mx-4 rounded-full cursor-pointer hover:bg-[#2546bd]'>
Login
</button>
) : (

<li className='bg-[#2952e3] py-2 px-7 mx-4 rounded-full cursor-pointer hover:bg-[#2546bd]'>
{truncateAddress(address)}
</li>
)}

The connect() method is derived from useCelo().

The await contract.methods.startProject() calls the startProject function in our CrowdFund.sol contract and passes in the required props defined in the contract.

Project Contract Instance

const fetchProjects = async () => {
const result = await contract.methods.returnProjects().call();
const data2 = []
for (let i = 0; i < result.length; i++) {
const projectContract = contractData
? (new kit.connection.web3.eth.Contract(
deployedContracts.abi,
result[i]
) as any as Project)
: null;
const data = await projectContract.methods.getDetails().call()
const structuredData = {
projectCreator: data.projectCreator,
projectTitle: data.projectTitle,
projectDescription: data.projectDescription,
projectImageLink: data.projectImageLink,
fundRaisingDeadline: data.fundRaisingDeadline,
projectGoalAmount: data.projectGoalAmount
}
data2.push(structuredData)
}
setResults(data2)
}

The fetchProjects function nested in the useEffect hook interacts with two contracts. The CrowdFund.sol to call the returnProjects()function to return the address of all created projects and then loop through these addresses to create a new instance of projectContract by passing the deployedContracts.abi which is the Project.solabi and result[i] which is the address of the projects created.

Note: Only the CrowdFund.sol was deployed. The Project.sol contract was not deployed. A new instance of the Project contract is created each time we want to interact with the contract methods.

After creating an instance of the contract, we call the await projectContract.methods.getDetails() which is a function in the Project.solcontract for returning the details of each created project.


Congratulations! 🥳

That brings to a close, today's topic on how to quickly build a CrowdFunding dApp on Celo. You can review each of the items we covered below and check that you've learnt each of them.

Here's a quick review of what we covered 🤔

  • ✅ Step 1: Setting up your environment.
  • ✅ Step 2: Create your smart contract.
  • ✅ Step 3: Deploy your smart contract.
  • ✅ Step 4: Getting started on the frontend.
  • ✅ Step 5: Interact with your smart contract from the frontend.
  • ✅ Step 6: Deploy your DeFi application.

Hopefully, you now have a good understanding of how to add and deploy your smart contracts on Celo and interact with them on the frontend. This project was created as an example of how to deploy on Celo and also use the Celo composer toolkit.

As a challenge, you could take it a step further by adding the functionality for contributing to a project and also disbursement of funds at the end of a project.

Till next time,

GN! 👋

Check out this project out on Github. Design Inspiration JavaScript Mastery

· 10 min read

Quickly develop Android and iOS apps on Celo using the Celo Composer for React Native.

header

Celo Composer is a set of templates created by Celo to reduce time-to-first-output for developers building dApps in the Celo Ecosystem. The objective is to improve the developer experience. The template is set up to work right out of the box, but also make customization as easy as possible.

In this article, you will go through the React Native version of the template. You will learn how to interact with smart contracts deployed on Celo blockchain using a react native dApp. If you plan to build or are already building mobile dApps on Celo 😁 consider reading till the end.

Here’s a list of things will we cover 🗒


Prerequisites

Before we get started you will need some packages and dependencies to be installed beforehand, here is a list of them.

  • Node v12+
  • Yarn / NPM
  • Python (node-gyp requires this)
  • windows-build-tools (only for windows)

Once you have the dependencies installed, it’s time we start setting up the template.


Setting up the project

celo-composer-on-github

  • Access the repo here.
  • Click the Use this template button to get it into your GitHub profile.

Once done, clone the repo to work on it on your local machine.

forking-repo

Once cloned we need to install expo and expo-cli globally since we are using Expo to build our app. Open up a terminal and use the below command or yarn global expo expo-cli to globally install expo and expo-cli.

npm i -g expo expo-cli

It’s time we install the package dependencies. In your terminal, navigate to <your_repo_name>/packages/react-native-app and use the below command in your terminal.

yarn install --ignore-engines

At this point, you are all set to start running the app on your local server use the command below.

expo start

Once the command is executed, you will see a QR code in the terminal like so.

qr-code-in-terminal

Thanks to Expo, there are various ways you can access your app.

expo-command-line-options

If you want to use Android Studio type A on the keyboard and it will start the Android Studio.

Note:- If you want to access using Android Studio make sure you have a Virtual Device with play store support.

If you press W it will open it in your web browser. In this tutorial, you are going to access the app using a mobile device. Because that’s how the user of your app will access it right?

In order to do so, we need to install the Expo Go App on our device of choice. Before we start using the app, we also need to deploy the smart contracts that we plan to interact with, so let’s do that now.


Deploying Smart Contracts

Smart contracts are like the backend to your dApp. Most of the logic resides in smart contracts. We are going to deploy contracts to the Alfajores testnet since I don’t expect you to use real funds in order to follow this tutorial.

You can see that in the file hardhat.config.json which is in the folder /packages/hardhat

hardhat.config.json

Before we deploy our contracts let us see which account we are going to use to deploy the contracts. You can use the below command in your terminal to do so. Make sure you are in the /packages/hardhat folder.

npx hardhat accounts

You can add your own account if you want. Let’s deploy the smart contracts using the below command in your terminal.

npx hardhat deploy --network alfajores

We specify the network we want to deploy to in the command.

terminal-output-for-smart-contract-deployment

You can see the transaction hash of the transaction and the address where the contract lives on the Alfajores chain.

file-structure

When you want to deploy fresh contracts you will need to delete the respective network folder.

You don’t need to worry about copying the contract addresses into the react-native-app project because we have wired it up in such a way that we pick up the address from the JSON files. 😃

Just to recap we are done with the following

🔳 Project Setup

🔳 App server On

🔳 Smart Contracts deployed

🔲 Get a Celo wallet (Valora for this tutorial)

🔲 Get some testnet funds.

🔲 Download the Expo Go App on your mobile device of choice

To interact with smart contracts on the blockchain we need a wallet specifically the Celo wallet in this case. For this tutorial, you will use the Valora wallet which is the preferred Celo wallet however you are free to use other wallets like Metamask but you won’t be able to use stablecoins as gas fees.


Downloading Testnet Valora

In this post, you’ll use the Alfajores testnet with the Valora app. This allows you to create dApps using test funds which allows you to avoid spending real money during development.

  • Download Celo Alfajores Wallet from the Play Store or App Store.

celo-testnet-wallet-play-store

Once downloaded Create New Account (recommended) you can also recover if you have a test account on Testnet.

valora-create-account-screen

Next, set up your account.

valora-onboarding

If you created a new account your balance will be zero and we need to have some funds to start interacting with the contracts deployed on the testnet.

valora-balance-screen

You can now get some funds from Celo Faucet so that we can interact with the deployed smart contracts. Even though you are using the app eventually you end up interacting with the smart contracts directly, the app is just an interface for user-friendliness.


Funding wallet with testnet coins

Copy your address.

valora-wallet-address

In the browser go to — https://celo.org/developers/faucet

funding-testnet-wallet

  • Paste your address, complete the captcha, and tap Get Started.
  • After a few seconds, if you go back to your app, you should see the token received from the faucet.

valora-balance-screen

Keep in mind these are not real funds 😄 these are required to interact with the testnet. You’re finally ready to play around the starter app. 🥳


Exploring the Mobile DApp

Scan the QR code shown in the terminal using the Expo App to open up the app on your device. The moment you see the Metro Bundler will start bundling the code and once that is done your device will start downloading it.

Once done you should have a screen like this.

dapp-main-screen

Note: At this point, if you get redirected to a browser and WalletConnect website, this means you are using Android 11 and above. There are steps to resolve this in the Github repo readme

Tap Connect Wallet to get a prompt to select the wallet of your choice. (For this tutorial Alfajores Wallet)

connect-wallet-prompt

You will see a screen prompting you to Allow the Starter app to get your account details like account address. Tap Allow.

connect-to-app-valora-screen

If successful you will see a notification like this.

valora-notification-screen

If you switch back to the Expo App you will see now that our account is connected.

greeter-app-screen

You can use the interface to interact with the standard Greeting Contract. The address underlined is the address of the Greeting Contract tapping will take you to the explorer.

Try tapping the Read Greeter Contract button and see if you get a greeting. Your output might be different since I have used it before.

greeter-read-result-screen

You can update the Greeting by using the input field. Once you have your greeting entered in the field tap the Update Greeter Contract.

greeter-write-operation-screen

Since you are doing a write operation on the contract we need to sign this transaction and it will cost you funds, don’t worry we are on testnet so we won’t be using real money.

valora-transaction-prompt-screen

You should see a screen like this, Alfajores is asking if you want to proceed with the transaction.

  • Click Allow to proceed this will perform an update on the Greeter Contract.
  • Once done if you switch back to the Expo App we can tap the Read Greeter Contract to see our update Greeting.

greeter-contract-read-result

Similarly, there is a screen for the Storage contract and an Account Info screen to view your account address and disconnect the wallet.

dapp-storage-and-account-info-screen

For now, these are all the screens we have but we are planning to add more. Expect more updates on this starter template. But wait there is more. 😲


Customizing the DApp

We have tried to provide a fair amount of customizations that can be done on the starter template and we at Celo working hard to make it easier and easier, to customize and also have plans to have various components that can help with mobile dApp development.

folder-structure-of-project

For now, here is a list of things you can do:

  • Add a splash screen: Add the splash screen image inside /assets/images
  • Change app colors: Edit Colors.ts in /constants
  • Add touchable opacity to buttons: Inside /components you will see I have added some modified TouchableOpacitycomponent to look like a button with color, feel free to edit it as you like.
  • Organize component styles: There is also a ThemeProvider.ts in /context which uses React Native StyleSheet for organizing styles for components, play with it as you like.
  • Organize your styles: It is not necessary to take the template as-is for design purposes, you can have your own way of code organization for colors and styles.
  • Add more screens: To add more screens to your app, there is /screens folder to add more screen files this is for code organization purposes.
  • Add to the interface: However, to add it to the interface check out the LinkingConfiguration.ts in /navigation
  • Add tabs: index.tsx inside /navigation has the code to the BottomTab navigation where you can add more tabs to various screens.
  • Add drawer navigation: After 3 to 4 screens BottomTab might not be the right choice to add more tabs so check out the docs to the Drawer Navigation.
  • Change app names: Refer to edit it inside index.js line number 15.
  • Add contracts: Add solidity files to in /hardhat/contracts

In the end, it is an Expo-based React Native project, so it can be customized as you want. Feel free to report any issues under the Issues tab in the Github repo and if you plan to contribute we will welcome you with open hands. 🤝


External References

Here are some links that can help if you wish to explore more.

  • React Native — Library to build cross-platform apps.
  • Expo — React Native Framework.
  • React Navigation — Library to help with navigation of screens.
  • Hardhat — Library to help with smart contract testing and deployment.
  • Solidity — Language used to write smart contracts.
  • WalletConnect — Library to access mobile install wallets in our dApps.

View on Medium ↗️