How to build a Simple Dapp on Celo Blockchain

How to build a Simple Dapp on Celo Blockchain https://celo.academy/uploads/default/optimized/2X/1/1df06d05eb59dda823a9cc1230c9ff7bb6b3fc0a_2_1024x576.png
none 0.0 0

Introduction

Decentralized Applications (DApps) are the future of the web. They offer users transparency, immutability, and security. Celo, a mobile-first blockchain platform, provides a great opportunity for developers to build DApps that can be accessed by users on their smartphones.

Prerequisites

In this article, no prior knowledge is required, I’ll make it as beginner-friendly as possible.

Requirements

Before we start, we need to set up our development environment. We will need to install the following tools:

  • Node.js
  • Yarn
  • Truffle
  • Celo Extension Wallet

Once you have installed these tools, you can move on to create our dapp.

Getting Started

In this article, we will walk through the steps involved in building a simple DApp on Celo.

Step 1: Create a New Project

To create a new project, open your terminal and run the following command:

mkdir my-dapp
cd my-dapp
npm init -y

This will create a new project directory called my-dapp and initialize a new package.json file.

Step 2: Install Celo Dependencies

Next, we need to install the Celo dependencies. Run the following command:

npm install web3 @celo/contractkit dotenv

This will install the @celo/contractkit package, which provides a JavaScript API for interacting with the Celo blockchain.

Step 3: Write Your Smart Contract

Now that we have set up our development environment and installed the necessary dependencies, we can start writing our smart contract.

Create a new file called SimpleDapp.sol and paste the following

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleDapp {
    string[] private messages;

    event MessageAdded(string message);

    function sendMessage(string memory message) public {
        messages.push(message);
        emit MessageAdded(message);
    }

    function getMessageCount() public view returns (uint256) {
        return messages.length;
    }

    function getMessage(uint256 index) public view returns (string memory) {
        require(index < messages.length, "Invalid index");
        return messages[index];
    }
}

In this example, we have a contract named SimpleDapp. It includes an array called messages to store the messages sent by users. The contract provides three functions:

  • sendMessage: Allows users to send a message, which is stored in the messages array.

  • getMessageCount: Returns the total number of messages stored in the messages array.

  • getMessage: Returns the message at a specific index in the messages array.

The sendMessage function emits an event MessageAdded whenever a new message is added, which can be used to notify listeners on the client-side.

Step 4: Compile and Deploy Your Smart Contract

Now that we have written our smart contract, we need to compile and deploy it to the Celo blockchain. Now, create a deploy.js file and copy the following code:

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

async function deployContract() {
  // Connect to the Celo network
  const web3 = new Web3('<CELO_NETWORK_URL>');
  const kit = ContractKit.newKitFromWeb3(web3);

  // Set the account to deploy the contract
  const privateKey = '<PRIVATE_KEY>';
  const account = web3.eth.accounts.privateKeyToAccount(privateKey);
  kit.connection.addAccount(account.privateKey);

  try {
    // Deploy the contract
    const SimpleDappContract = require('<PATH_TO_COMPILED_CONTRACT_JSON>');
    const contract = new web3.eth.Contract(SimpleDappContract.abi);

    const contractDeploy = contract.deploy({
      data: SimpleDappContract.bytecode,
    });

    const gas = await contractDeploy.estimateGas();
    const transaction = contractDeploy.send({ from: account.address, gas });

    const deployedContract = await transaction;
    console.log('Contract deployed:', deployedContract.options.address);
  } catch (error) {
    console.error('Contract deployment failed:', error);
  }
}

deployContract();

Make sure to replace the following placeholders in the code with the appropriate values:
<CELO_NETWORK_URL>: The URL of the Celo network you want to connect to.
<PRIVATE_KEY>: The private key of the account that will deploy the contract.
<PATH_TO_COMPILED_CONTRACT_JSON>: The path to the compiled contract JSON file, which contains the contract’s bytecode and ABI.

Ensure that you have the necessary dependencies (@celo/contractkit and web3) installed in your project. You can install them by running npm install @celo/contractkit web3 or using yarn if you prefer.

Once you have replaced the placeholders and executed the script, it will deploy the SimpleDapp contract to the Celo network using the specified account. The deployed contract’s address will be logged to the console.

Step 5: Create Your Frontend

Now that we have deployed our smart contract, we can create our frontend to interact with it.

Create a new file called index.html in the root directory and paste the following code:

<!DOCTYPE html>
<html>
<head>
  <title>Simple Dapp</title>
  <style>
    /* Add some basic styling */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
    }
    h1 {
      margin-bottom: 20px;
    }
    input, button {
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <h1>Simple Dapp</h1>
 
  <div>
    <input type="text" id="inputText" placeholder="Enter your message">
    <button onclick="sendMessage()">Send Message</button>
  </div>

  <div id="messages">
    <!-- Messages will be displayed here -->
  </div>
 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.5.3/web3.min.js"></script>
  <script src="./app.js"></script>
</body>
</html>

This creates a simple HTML page with an input field to set the value and buttons to set and get the value.

Create a new file called app.js in the root directory and paste the following code:

// Import Web3 library and initialize the contract
const web3 = new Web3(new Web3.providers.HttpProvider('https://your-celo-node-url'));
const contractAddress = '0x...'; // Replace with your smart contract address
const contractABI = [/* Replace with your contract's ABI */];
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Function to send a message to the smart contract
async function sendMessage() {
  const message = document.getElementById('inputText').value;

  // Send the message to the smart contract
  await contract.methods.sendMessage(message).send({ from: web3.eth.defaultAccount });

  // Clear the input field
  document.getElementById('inputText').value = '';
 
  // Refresh the messages
  fetchMessages();
}

// Function to fetch and display the messages from the smart contract
async function fetchMessages() {
  const messagesDiv = document.getElementById('messages');

  // Clear existing messages
  messagesDiv.innerHTML = '';

  // Get the number of messages stored in the smart contract
  const messageCount = await contract.methods.getMessageCount().call();

  // Fetch each message and display it
  for (let i = 0; i < messageCount; i++) {
    const message = await contract.methods.messages(i).call();
    messagesDiv.innerHTML += `<p>${message}</p>`;
  }
}

// Set the default account for transactions
web3.eth.getAccounts().then(accounts => {
  web3.eth.defaultAccount = accounts[0];
});

// Fetch messages when the page loads
fetchMessages();

This code connects to the Celo network and provides functions to set and get the value of our smart contract.

Replace the contractAddress variable with the address of your deployed smart contract.

Step 6: Run Your DApp

To start the server using an npm command, follow these steps:

  1. Open your project’s package.json file.

  2. Locate the scripts section and add a new script entry for the server. For example:

"scripts": {
    "start": "http-server -c-1"
},
  1. Save the changes to the package.json file.

  2. Open your project’s terminal and navigate to the project’s root directory.

  3. Run the following command to start the server:

npm run start

This command will execute the script defined in the start entry of your scripts section, which in this case is http-server -c-1. The server will start, and your Dapp will be served at the specified local address, typically http://localhost:8080.

Make sure you have the http-server package installed as a dependency in your project by running npm install http-server. If you have already installed it previously, you can skip this step.

By using the npm run start command, you can start the server and access your Dapp locally.

Open your web browser and navigate to http://localhost:8080. You should see your DApp, and you can set and get the value of your smart contract.

Lastly, should you want to push your code to GitHub, create a .gitignore file and type node_modules

Congratulations! You have built a simple DApp on Celo.

Conclusion

In this article, we have walked through the steps involved in building a simple DApp on Celo. We have created a smart contract, compiled and deployed it to the Celo blockchain, and created a frontend to interact with it.

Next Steps

Celo provides a great platform for building DApps, and we encourage you to explore its capabilities and build your own DApps on Celo. You can do this is through our tutorials

About the Author

Joel Obafemi

A marketer, copywriter, and collab manager for web3 brands. You can connect with me on LinkedIn.

References

1 Like

Approved for you to get started. You can manage the tutorial here by changing the category to Proposals > In Progress then Proposals > Review as you complete the tutorial. Thanks!

@joenyzio I’m done with this article and it’s ready for review.

I’ll be reviewing your piece :+1:

Oh great. How do I proceed?

Still trying to get the hang of it myself, but you should be able to add your tutorial in markdown here,

Have you written your piece already?

Yes I have. I’ve attached it to my proposal.

Noice I’ll leave comments soon

Review Suggestions

  1. Hi @Joel about your piece,
    You can remove the slug, and table details up onto the header image and let your piece start from Introduction

Thanks @Phenzic

I’ve made that edit. Is there anything else you’ll like me to fix?

Cool, your piece seems precise … good :ok_hand:
Moving to publish

1 Like