Tutorial: Creating an Ethereum-backed Web3 Chat

In this article, we will learn how to connect an Ethereum smart contract to a React application and enable users to interact with it.

prerequisites

  • To install the MetaMask extension in your browser
  • a code editor
  • Some knowledge about the following topics: Ethereum, MetaMask, React, TypeScript

Working on the Ethereum mainnet costs real money!

In this tutorial, I am assuming that your MetaMask is set up to use Rinkeby. Rinkeby is a testnet that replicates the mainnet, allowing us to deploy and use smart contracts for free.

project

We will build an interface for this blockchain-based chat as follows:

Tutorial: Creating an Ethereum-backed Web3 Chat

  • The left sidebar contains a button to connect to the chat or to indicate the address of the connecting user.
  • The chat box on the right, showing the message and input fields.

In this article, we won’t focus on how to make the UI more beautiful, our goal is to focus on how to interact with smart contracts in the most direct way.

I’ve tried my best to make this tutorial easy to understand, but don’t be discouraged if something isn’t clear, you’ll find a link to a GitHub repository containing the completed project at the end of this article.

smart contract

First, we want to connect to the front-end smart contract as follows:

WPUDlrDxo0LBY1JggLB4zdn4GX2A6OHqFEf00E0a.png

What are event and emit?

event is used to notify external users of what happened on the blockchain.

In our case, the “external user” is our front-end application that will listen for new messages sent to the smart contract, so we can display them in our UI right away.

front end

I’ve prepared a boilerplate so you can start coding right away.

Here is the Github link to start the project:

https://github.com/thmsgbrt/web3-chat-powered-by-ethereum-starter

Once you’ve cloned the project, installed the dependencies with npm install, and started it with npm start, it’s also worth taking a few minutes to examine a few files to see how the application is constructed. This is very basic React, so I won’t go into details here.

Here is our action plan:

A – Allow users to connect to chat via MetaMask

B – Instantiate the smart contract in our frontend

C – get messages from our smart contract and display them

D – Allows users to post messages in chat

E-Listen to new information

A – Allow user to connect to chat via MetaM ask

To do this, we first need to make sure that the MetaMask extension is installed on the browser.

Let’s create a Hook to achieve this:

crxZ5IKCp8sFEiN5Fm34ekZtOk1t2y108HotyJFm.png

explain:

MetaMask injects a global API in window.ethereum. The API allows websites to request the user’s Ethereum account, read data from the blockchain the user is connected to, and advise the user to sign messages and transactions.

Now that we have our Hook ready, turn to Sidebar.tsx so we can take advantage of it:

hKRsKuyFzTGeDiOHhE6xoz4A3XVLs23gLrJKyJOk.png

1YbF9fl05btX2ZcGzOrHmBQBo6leVxS7edhNsUf5.png

As of now, we have a way to detect if MetaMask is installed, and if MetaMask is not installed, we can warn the user that they need to install MetaMask on their browser.

Next, let’s add an onClick handler for the “Connect With MetaMask” button:

r4XOBHfmP9jLD1PWqyZpuuPXnFdxBmwfaSBvQNqa.png

VFxVikiHUfUp13EcX5bO1nTmeTT2vi6OFrWOnlsU.png

Now, when the user clicks Connect With MetaMask, the MetaMask extension will prompt a modal and ask which account to use:

Tutorial: Creating an Ethereum-backed Web3 Chat

MetaMask asks us to connect to our chat

Tutorial: Creating an Ethereum-backed Web3 Chat

Connected now!

The sidebar now shows your Ethereum address!

B – Instantiate the smart contract in our frontend

To be able to get information and enable users to send messages, we need to have a way to communicate with our smart contract.

We are going to use the ethers library.

ethers is a library that helps our frontend talk to smart contracts. ethers are connected to Ethereum nodes through a provider (MetaMask in our case), which can do a lot of things for us.

Let’s create another Hook that will allow us to interact with our smart contract with the help of ethers:

GOC2oHLtErUUJSMiKhpm3tiw6luARLvApqti0VN5.png

pdUMizFWuW5liflPHVXmkRnw6nPzCQfsdKDUpYmi.png

Let’s break it down:

  • Let’s first check if window.ethereum exists and get the Web3 Provider from it.
  • If accountis is defined, which means the user clicked the “Connect With MetaMask” button, webThreeProvider.getSigner() will return us their address.
  • Finally, return a contract instance with a new ether.contract().

Instantiate our smart contract

Head over to App.tsx, where we can use the hook we created:

tzJXdalFDANTMskUcczFNH2of2QYgntjj1t5glEQ.png

Did you notice that we have a bug here and need to do two things to fix the problem:

  • contractAddress is not a contract address.
  • ./contract/BlockchainChat-artifact.json is empty.

contract address

This address tells us where to find the blockchain chat smart contract on the blockchain.

You can use one of the following addresses where I deploy to Rinkeby for everyone:

  • 0x56cD072f27f06a58175aEe579be55601E82D8fcD
  • 0xD99f113cAd1fe2eeebe0E7383415B586704DB5a3
  • 0x23CAEEA0Bb03E6298C2eAaa76fBffa403c20984f

Pick any of them, they are all addresses that point to the deployed blockchain Chat smart contract.

ABI of the contract

Our Hook expects an ABI from BlockchainChatArtifact. Here are two new concepts…

When you compile a smart contract, you get what are called artifacts.

In Remix (an IDE for creating, compiling, testing and deploying smart contracts), once your smart contract has been compiled, you will find artifacts under contracts/artifacts.

This artifact contains the library’s link, bytecode, deployed bytecode, gas estimates, method identifiers, and ABIs. It is used to link the library address to the file.

Now, what is “ABI”:

ABI stands for Application Binary Interface. ethers need the ABI of our BlockchainChat smart contract in order to know what our smart contract can do (methods, events, errors, etc.) and provide a way for our front end to interact with it.

If you did not deploy the smart contract yourself, you can still continue this article by copying the following artifacts in ./contract/blockchainchat-artifacts.json.

Gist link to artifact:

https://gist.github.com/thmsgbrt/1db36bc688d6984070badb14652ed65c

The application should now be error free!

C – get messages from our smart contract and display them

Now that we have instantiated the smart contract on the front end, we can finally get the message. Open Chat.tsxand add the following getMessagesfunction:

yvAY8WAtW4tmt0Ls1bydGi7G8CufUePMKTuv5djj.png

080y9q8Ax866RVGaVxP2vUwLrZ8JGiiSZVUWzF5c.png

cGLR8Mfr0bdcdkXCeb1EAMEiUCBL6bzHjQqyGqy8.png

Chat.tsxReceives an instance through its props chatContract, which we can use to call chatContract.getMessages(). With received messages, we populate messagesstate variables.

If your chat smart contract publishes messages, they should be visible in the chat box. Otherwise, let’s go ahead and allow the user to send messages. Here’s what you should see so far:

Tutorial: Creating an Ethereum-backed Web3 Chat

D – Allows users to post messages in chat

In Chat.tsx, add the following sendMessagefunction to publish the message:

EymDybfpguzMXFTNQAW2QsvE8nGXHfYW72B3NIjo.png

F7V1PWVFY9C6J7lF6VL1kKJwN8VNZZVktruiX4cH.png

eP1BqDtGIR7fuuGdYvCz3W1Z1FfcVhKxHwXOW5Ws.png

Tutorial: Creating an Ethereum-backed Web3 Chat

Z1jnLmZToJ6k7lrGsJP74xJlxz8XeM5SrKApZSMO.png

Let’s go ahead and enter a message in the textarea and send it! This should prompt MetaMask to verify the transaction, continue:

Tutorial: Creating an Ethereum-backed Web3 Chat

The “send message” button in our UI has different states. Its content changes depending on the transaction status:

  • “WAIT” means that the transaction requires user approval.
  • “SENDING” means the transaction is being verified.

To see the message just posted, reload the page. It should be added.

But in terms of user experience, having to reload the page to see if a new message is posted is not very friendly.

E – Listen to new information

Back to our smart contract. As you can see, when the user posts a message, an event is fired:

K7ANudHbVAlsE3UwCVNOGu5GulHYRwXAI7c8hRHP.png

We can listen for this event by adding the following setupMessageListener function:

yT1TjRxGib0GfkBv0G0zhisRpCsQWCPtydLn32rw.png

NfcVs3D6ndEatvv64uqcmzkagx2eij8i1K9xsxZ7.png

mhupvkMBsa4Cm1QqCSJnuWdi78xSES3IxnsTptk5.png

FQoXiKy2NBUfkBX3znvFFlEQn2jSHnymoHOW0qs8.png

21zeU4UJJY0RnJQEGnAUIE1z0zjRlI00KLGcwbLG.png

Next, send a new message, and this time, you shouldn’t have to reload the page to see the message just posted. This obviously also works if another user sends a message.

Tutorial: Creating an Ethereum-backed Web3 Chat

final project

Congratulations on completing this tutorial. As promised above, here is a link to the final project:

https://github.com/thmsgbrt/web3-chat-powered-by-ethereum-finished-project

Posted by:CoinYuppie,Reprinted with attribution to:https://coinyuppie.com/tutorial-creating-an-ethereum-backed-web3-chat/
Coinyuppie is an open information publishing platform, all information provided is not related to the views and positions of coinyuppie, and does not constitute any investment and financial advice. Users are expected to carefully screen and prevent risks.

Like (0)
Donate Buy me a coffee Buy me a coffee
Previous 2022-07-01 09:56
Next 2022-07-01 10:02

Related articles