Deploying and Interacting with Smart Contracts on Celo: A Hands-On Tutorial

Deploying and Interacting with Smart Contracts on Celo: A Hands-On Tutorial https://celo.academy/uploads/default/optimized/2X/1/11e5183c83aac6ffa510f21a6a468b2075693842_2_1024x576.jpeg
none 0.0 0

Introduction

Smart contracts have revolutionized the world of blockchain technology by enabling self-executing contracts with the terms of the agreement directly written into code. Celo, a blockchain platform, provides a robust ecosystem for deploying and interacting with smart contracts. In this hands-on tutorial, you will learn how to deploy and interact with smart contracts on the Celo network.

Prerequisites

To make the most of this tutorial, you should have a basic understanding of blockchain technology and smart contracts. Familiarity with the Solidity programming language is also beneficial, as we will be writing and deploying smart contracts using Solidity.

Requirements

Before we begin, ensure you have the following:

  • A computer with an internet connection
  • A text editor or integrated development environment (IDE) for writing Solidity code
  • Node.js and npm (Node Package Manager) installed
  • Celo CLI (Command Line Interface) installed

Setting Up the Development Environment

  1. Install Node.js and npm: Visit the Node.js website (https://nodejs.org) and download the latest stable version suitable for your operating system. Follow the installation instructions to install Node.js and npm.

  2. Install Celo CLI: Open a terminal or command prompt and run the following command to install the Celo CLI globally:

npm install -g celocli
  1. Verify the installation: Run the following command to verify that the Celo CLI is installed correctly:
celocli --version

You should see the version number displayed if the installation was successful.

Creating a Celo Wallet

  1. Generate a new Celo account: Run the following command to generate a new Celo account, which will serve as your wallet:
celocli account:new

Take note of the generated account address and the corresponding private key. They will be necessary for deploying and interacting with smart contracts.

  1. Fund your account: To interact with smart contracts on the Celo network, you will need some CELO (Celo native token) and Celo Dollars (cUSD). You can request testnet funds from the Celo faucet or use a testnet exchange to obtain testnet CELO and cUSD.

Writing a Smart Contract

  1. Open your preferred text editor or IDE and create a new file named “MyContract.sol”.

  2. Write the smart contract code in Solidity. For example, consider a simple contract that stores and retrieves a single string:

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

contract MyContract {
    string private myString;

    function setString(string memory _newString) public {
        myString = _newString;
    }

    function getString() public view returns (string memory) {
        return myString;
    }
}
  1. Save the file with the “.sol” extension.

Deploying the Smart Contract

  1. Compile the smart contract: In the terminal, navigate to the directory where the “MyContract.sol” file is saved. Run the following command to compile the smart contract:
celocli compile MyContract.sol

This will generate the compiled bytecode and ABI (Application Binary Interface) JSON files.

  1. Deploy the smart contract: Run the following command to deploy the smart contract to the Celo network:
celocli contract:deploy MyContract --args <constructor-arguments> --from <your-account-address>

Replace <constructor-arguments> with any required constructor arguments, if applicable, and <your -account-address> with your Celo account address.

  1. Take note of the deployed contract address: After a successful deployment, the CLI will display the deployed contract address. Save this address for future interactions with the smart contract.

Interacting with the Smart Contract

  1. Create a new JavaScript file named “interact.js” in your text editor or IDE.

  2. Install the required packages: Run the following command in the terminal to install the necessary packages for interacting with the smart contract:

npm install celo-sdk
  1. Import the required modules and initialize the Celo SDK:
const ContractKit = require('@celo/contractkit');

async function interactWithContract() {
    const kit = ContractKit.newKit('https://<celo-network-url>');

    // Set the appropriate network URL (e.g., Alfajores testnet: https://alfajores-forno.celo-testnet.org)

    // Set the private key for your Celo account
    const privateKey = '<your-private-key>';
    const account = kit.web3.eth.accounts.privateKeyToAccount(privateKey);

    // Add your account to the kit instance
    kit.addAccount(account.privateKey);

    // Get an instance of the deployed smart contract
    const contractAddress = '<deployed-contract-address>';
    const contract = new kit.web3.eth.Contract(<contract-abi>, contractAddress);

    // Interact with the smart contract using contract.methods

    // Example: Call a function that retrieves a value from the smart contract
    const result = await contract.methods.getString().call();
    console.log('Value retrieved from the smart contract:', result);

    // Example: Call a function that sets a new value in the smart contract
    await contract.methods.setString('New Value').send({ from: account.address });

    // Example: Call the getter function again to verify the updated value
    const updatedResult = await contract.methods.getString().call();
    console.log('Updated value from the smart contract:', updatedResult);
}

interactWithContract();
  1. Replace <celo-network-url> with the appropriate Celo network URL (e.g., Alfajores testnet), <your-private-key> with your Celo account’s private key, and <deployed-contract-address> with the address of the deployed smart contract.

  2. Save the file.

Running the Interactions

  1. In the terminal, navigate to the directory where the “interact.js” file is saved.

  2. Run the following command to execute the interactions with the smart contract:

node interact.js

You should see the output in the console, displaying the retrieved and updated values from the smart contract.

Conclusion

Congratulations! You have successfully learned how to deploy and interact with smart contracts on the Celo network. This tutorial covered the setup of the development environment, creating a Celo wallet, writing a simple smart contract in Solidity, deploying the contract, and interacting with it using JavaScript.

Next Step

Now that you have a basic understanding of deploying and interacting with smart contracts on Celo, you can explore more advanced concepts such as contract inheritance, event handling, and integrating with frontend applications. Consider exploring the Celo Developer Documentation and Solidity documentation for further learning.

About the Author

Oyeniran Adeolu, a skilled content writer, excels in transforming intricate technical concepts into easily understandable content. With a fervor for clarity and conciseness, I am dedicated to delivering exceptional work. Let’s connect on LinkedIn. Together, we can bring your technical ideas to life, captivating and informing your audience in a way that sets you apart.

Reference

Celo Documentation
Github Repo
Solidity Documentation

4 Likes

Congratulations on being among the top voted proposals this week! This is now approved by @Celo_Academy for you to get started whenever you’d like. :mortar_board: :seedling:

2 Likes

Thank you.

However, I’ve been trying to gain access to edit the article but I couldn’t. Can you help with that please?

1 Like

I’ll be reviewing this @DeoJay

2 Likes

Ok. Thank you @Jorshimayor

1 Like