Create an HBAR Faucet App Using React and MetaMask
Enabling the opportunity to connect to a decentralized application (dApp) with different wallets provides more control to the user. Recently, HIP-583 added the necessary network infrastructure to support Ethereum Virtual Machine (EVM) wallets on the Hedera network. This added functionality, combined with the auto-create flow described in HIP-32, enables developers to transfer native Hedera Token Service (HTS) tokens to EVM addresses that do not yet exist on the Hedera network. In this tutorial, we start out with a Hedera react app, connect our dApp to MetaMask, and finally transfer HBAR to the connected MetaMask account.
What we will do:
This tutorial will show you how to create a Hedera React app using TypeScript and Material UI. You'll install the MetaMask Chrome extension, add the Hedera Testnet network, connect your dApp to it, and even send some HBAR to your MetaMask wallet.
Prerequisites
Create a Hedera Testnet account here.
Install the MetaMask Chrome extension.
Basic understanding of TypeScript and React.
Set up your environment and create your client here.
Table of Contents
Create React App
Open your terminal and run the following command to create a React app that utilizes TypeScript and Material UI.
This creates react-app theme that provides a navbar with a button, footer, react-router, and a global context for state management. We will use this template to kickstart our project.
Open the project in Visual Studio code or your IDE of choice. Your project directory structure will look like this:
If you have not already installed the MetaMask Chrome extension, please install it here.
Configure MetaMask with Hedera Testnet Network
In this step, we will add the code necessary to add the Hedera Testnet network to MetaMask so we can connect to it. Before we do that, let’s check out our project folder structure, which looks like this:
Let’s continue and add a new folder inside src and name it services. Inside the services folder, add a file named metamaskService.ts
. Your src
folder structure will look like this:
We will store the code in the services folder, which will be used to support certain services required to run our application. We added the metamaskService.ts file
to hold the code necessary for our MetaMask integration with our application. This distinction helps keep our code organized and clean.
It’s important to note that to add the Hedera test network to MetaMask, we must determine if MetaMask exists in our browser. We can achieve this by using the window, aka the Browser Object Model (BOM), which represents the browser's window. This window object can access all global JavaScript objects, functions, and variables. If we are successful in accessing the Ethereum object off of the window object, then it is an indication that MetaMask is installed. If it is not successful, then we will handle that by throwing an error message to the console that reads, “MetaMask is not installed! Go install the extension!”
Let's begin!
In our metamaskService.ts file
, create a function named switchToHederaNetwork
.
Let’s digest this function a little further. This function starts by submitting a request to change to the network to Hedera Testnet. If it fails to connect due to the Hedera Testnet network not being configured in MetaMask, then we will submit a request to add a new chain. In the request to add a new chain, the decimal value is set to 18 even though HBAR has 8 decimals. The reason for this is that MetaMask only supports chains that have 18 decimals. The RPC URL we use is https://testnet.hashio.io/api, which comes from Hashio, the SwirldsLabs-hosted version of the JSON-RPC Relay.
Connect Our dApp to MetaMask and Retrieve Wallet Address
We have added the code necessary to configure MetaMask with the Hedera test network. Now, it's time to focus on adding the code that will allow us to connect our dApp to MetaMask.
In the metamaskService.ts
file underneath switchToHederaNetwork(), add a new function named connectToMetamask().
If MetaMask is installed, connectToMetamask() will call switchToHederaNetwork() and submit a request to get accounts.
Before we do any kind of work or testing, it is important to ensure we are connected to the correct network.
Install Dependencies
We’ve written the code to connect our application to MetaMask. Now it’s time to send HBAR to our MetaMask wallet.
Install the Hedera JavaScript SDK and dotenv by running the following command in the project root directory:
Create your .env
file by adding a new file to the root directory of your react-app and naming it .env. Next, add the .env
file to your .gitignore
to prevent sharing your credentials in source control.
Your .env
file will look like this:
In a react-app, the environment variables in your .env file must start with REACT_APP_. Set the values to the testnet account you created through the Hedera developer portal.
Note: If you need to create a Hedera Testnet account, visit portal.hedera.com and register to receive 10,000 testnet HBAR.
Create Your Client
A client is used to communicate with the network. We create our client for the Hedera Testnet, which enables us to submit transactions and pay for them. Let’s create our client in our Home.tsx
file.
Build Your TransferTransaction
In our services folder, add a new file and name it hederaService.ts
. This file will hold the code to send HBAR to our MetaMask wallet. Inside the file, let’s create a function and name it sendHbar.
This function builds a TransferTransaction that will send a specified amount of HBAR from one account to another. In our case, our from account is our developer portal account, and our to account is our MetaMask wallet address.
Once the transaction is built, we approve it by signing it with our private key by calling .sign(). We call .execute() on our signed transaction using the client to pay for the transaction fee.
When a transaction is executed, the result is of type TransactionResponse. Use the transaction id from the TransactionResponse in a TransactionReceiptQuery to get a TransactionReceipt, including children transactions.
You can learn and read more about parent and child transactions on our documentation site.
Note: For security purposes, the account sending the tokens should be on a backend server, but for simplicity, it will be on the frontend. This is a reminder that private keys should never be exposed on the frontend, as that is the easiest way to lose control of your account.
Send HBAR to MetaMask Wallet
We’ve written the code necessary to connect our application to MetaMask and installed the Hedera JavaScript SDK. Now it’s time to focus on connecting all the parts and sending HBAR to our MetaMask wallet.
Configure State Management
React has a feature called Context that allows you to easily pass data between components without prop drilling. We will be leveraging this feature to save the MetaMask wallet address and enable us to access it from various components in our react-app.
Let's edit our src/contexts/GlobalAppContext.tsx
file, which came with our template, to look like this:
Add Functionality to the NavBar Button
Once we’ve set up our context, we use it to share the application state throughout the app. We use the context by calling useContext() and passing in GlobalAppContext as an argument. This allows us to get and set the wallet address from anywhere in the app.
Add the following code to the top of the file src/components/Navbar.tsx
:
Next, we will create a new function to connect to MetaMask and store the wallet address in the GlobalAppContext.
Now we can add an onClick to our button and change the text to say 'Connect to MetaMask`. onClick will call retrieveWalletAddress.
Your completed button code will look like this:
Add Send HBAR Button
In the Home.tsx
file, we will call our global context to gain access to our metamaskAccountAddress state variable.
Next, add a new button to send HBAR to our MetaMask wallet. After the closing tag </Typography>, create a material UI button and add onClick. The onClick will call sendHbar(), which is inside src/services/hederaService.ts.
The to address will be the metamaskAccountAddress that we pulled out from our context using useContext(GlobalAppContext).
Your completed button code will look like this:
We’re ready to run our application! Open a terminal In the root directory of the project and run:
Once up and running, click on the ‘Connect to MetaMask’ button in the upper right-hand corner.
After you click on it, the MetaMask pop-up window will open, and you will be asked to switch from your previously connected network to the Hedera Testnet.
Choose the account that you would like to connect to this application.
Debugging tip: If you have previously connected your account to this dApp and clicking connect is not opening the wallet, disconnect all the connected accounts and then try again
Once connected, send HBAR by clicking on the ‘SEND HBAR TO METAMASK’ button. You can open your console and see that the transaction response is printed to the console.
Summary
You learned how to build a transfer transaction that sends an amount of HBAR through the Hedera Testnet to a MetaMask account. This can also be applied to other applications, and I encourage all to keep building.
Congratulations! 🎉 You successfully followed the tutorial to create an HBAR faucet for MetaMask and a Hedera React application that integrates with MetaMask! Feel free to reach out in Discord if you have any questions!
Additional Resources
➡ TypeScript Project Repository
➡ JavaScript Project Repository
➡ Have a question? Ask on StackOverflow
Last updated