Interacting with Smart Contracts using ethers.js
How to interact with smart contracts deployed on Mode AI from a frontend using ethers.js
In this tutorial, we'll walk through setting up a basic web app, deploying a smart contract on Mode AI Network's testnet, and interacting with it using ethers.js.
If you want a quickstart and just get to the code, go to this repository and follow the readme guide to run it. We will walk you through the code in this tutorial.
Prerequisites
-
Add Mode AI Testnet to your metamask using the network info from here:
-
Get test ETH sepolia here: Testnet Faucets
-
Bridge to Mode AI Testnet here: Bridging to Testnet
-
Have Node and NPM installed on your PC
-
Have a basic understanding of React.js and how blockchain works
Smart Contract Deployment On Mode
We've crafted a simple smart contract named BidBoard for this tutorial. The contract allows advertisers to bid for space on an advertising board. The code and deployment details are available on this GitHub repository and Mode AI Testnet Explorer. You can also write your own custom smart contract and deploy it to Mode by following Deploying a Smart Contract.
Getting Started
Now that we have the prerequisites, the first thing we need to do is to open our terminal, navigate into the folder where you want your project to be, and create a simple react app by running the following command
npx create-react-app bidboard-ui
It should create the whole React App for you.
Install Ether.js
Ethers.js is a sleek library facilitating the interaction between web applications and blockchain. In the App component, we are using ethers.js to interact with our smart contract and also listen to events being emitted from the smart contract. To install ethers.js, navigate into the project you just created and run the following command:
npm install ethers
Create Main App Component
You can open up the project in VSCode or any other code editor
of your choice and then open the
App.js
file
Replace all the code and paste this:
In this file are importing
useState
and
useEffect
which we'll be needing later in this tutorial, weβre also
importing
ethers
to enable us to make a connection to our smart contract.
The next thing we need to do is to declare our contract address and ABI file, there are different ways get the contract ABI but if you deployed you smart contract using foundry, you can find your ABI check the following directory:
./out/MyContract.sol/MyContract.json.
On the frontend side of things, weβre going to update our
App.js
adding these lines:
Your
App.js
should look like:
We added the contract address, the abi, and a few states that we will need for our dApp to work. Don't worry about all these React states, they are particular for this app so you don't need to fully understand them. Please remember to paste you ABI in your App.js file.
Usually we would save the ABI in a different file and then import it but in this case we'll just paste all the ABI JSON in our App.js file.
Set the Provider
As the page loads, we'll set our provider to immediately fetch the current advertisement details from our smart contract, as demonstrated in the code below.
This code is using the
useEffect
hook in React to execute once after the component mounts. If the
window
object and
window.ethereum
are defined, it sets a new provider using
ethers.BrowserProvider
to interact with the Ethereum blockchain. If
window.ethereum
is not defined, it logs an error asking to install MetaMask, a
browser extension for managing blockchain transactions.
Fetch Current Advertisement Data
Create a function to fetch the current advertisement data from
our contract and call this function inside a
useEffect
hook.
In the above code weβre fetching the current ad by setting our
provider like we did before, creating a new instance of our
contract by passing in the contract address, contractABI and our
provider and then invoking the
getCurrentAd
function from our smart contract which returns the current
adData. Then we pass the adData into our app state so we can
render them in the frontend.
Update Our Smart Contract State
Now weβre able to fetch the current state of our contract we also need to be able to update the state and thatβs what the below function does
In summary, the
submitBid
function allows users to submit a new bid to the smart contract.
It initializes a contract instance and a signer, creates a
transaction to update the advertisement message with the new
bid, and waits for the transaction to be confirmed on the
blockchain.
If any errors occur during this process, they are caught and logged, and the user is informed about the error through a status message.
Listening to events on our Smart Contract
Consider you're bidding for ad space, and someone else places a higher bid. It's essential to know about this new bid immediately. This is where event listening helps: it can notify you about the latest bid in real-time, keeping you updated on the bidding activity.
The following code sets up an event listener:
This above code sets up an event listener using the useEffect
hook to listen for the
MessageUpdated
event emitted by the smart contract whenever the advertisement
message is updated.
When such an event is detected, it updates the state variables
currentAd
,
currentBid
, and
advertiser
with the new message, advertiser, and bid amount, respectively.
This ensures that the displayed data on the web app remains
synchronized with the blockchain.
Lastly, it provides a cleanup function to remove the event listener, preventing potential memory leaks when the component is unmounted or re-rendered.
Code The UI
Thatβs it, weβre done with the on-chain functionalities, now
letβs build UIs to test them out. How you choose to build your
UI is entirely up to you, for our project, weβre just going to
add the following JSX to our
App.js
code:
Running the project
To run the project open your terminal and run the following command in the project's folder:
npm start
Your console should look similar to this:
Open the URL shown in your browser and you are good to try your dApp!
Conclusion
This tutorial provided a hands-on journey through creating a web application and connecting it to a smart contract deployed on Mode AI Testnet using ether.js.
Through this project, we delved into essential steps from setting up the development environment to real-time tracking of smart contract events. You can clone the code and play around with it!\
To learn more about Mode AI and how to turn your code into a business, join our Telegram and say hello π
Last updated
Was this helpful?