Create a Hedera DApp Integrated with WalletConnect
In the dynamic world of decentralized applications (DApps), catering to users with diverse wallet preferences is important.
Explore DApp development using the Mirror Node API and Hedera Token Service (HTS). Discover how to integrate HTS functionality into your DApp for seamless token management and transactions. This guide uses React, Material UI, Ethers, and TypeScript with the Create React App (CRA) Hedera DApp template integrated with walletconnect, streamlining your development process.
What you will accomplish

Prerequisites
Before you begin, you should be familiar with the following:
Get Started
We choose to scaffold our project by using the CRA Hedera DApp template, as it offers:
This custom template eliminates setup overhead and allows you to dive straight into the core features of your project.
1. Scaffold your project
Open a terminal and run the following command to set up your project structure, replacing my-app-name
with your desired directory name.
npx create-react-app <my-app-name> --template git+ssh://[email protected]/hedera-dev/cra-hedera-dapp-template.git
Open your newly created react app project with visual studio code. You should see the following file structure.

2. Fetching Token Data: Writing Mirror Node API Queries
Mirror nodes offer access to historical data from the Hedera network while optimizing the use of network resources. You can easily retrieve information like transactions, records, events, and balances. Visit the mirror node API docs to learn more.
In vscode open the file located at src/services/wallets/mirrorNodeClient.ts
.
This file creates a mirror node client and is used to fetch data from the mirror nodes. We will add new code to help us obtain information about the tokens we currently own.
2.1 Query Account Token Balances by Account ID
We'll use the Mirror Node API to query information about the tokens we currently own and the quantities of those tokens.
Open src/services/wallets/mirrorNodeClient.ts
and paste the below interface outside of and above the MirrorNodeClient
class.
export interface MirrorNodeAccountTokenBalance {
balance: number,
token_id: string,
}
Paste the below HTTP GET request outside of and below the MirrorNodeClient
class in the src/services/wallets/mirrorNodeClient.ts
file.
// Purpose: get token balances for an account
// Returns: an array of MirrorNodeAccountTokenBalance
async getAccountTokenBalances(accountId: AccountId) {
// get token balances
const tokenBalanceInfo = await fetch(`${this.url}/api/v1/accounts/${accountId}/tokens?limit=100`, { method: "GET" });
const tokenBalanceInfoJson = await tokenBalanceInfo.json();
const tokenBalances = [...tokenBalanceInfoJson.tokens] as MirrorNodeAccountTokenBalance[];
// because the mirror node API paginates results, we need to check if there are more results
// if links.next is not null, then there are more results and we need to fetch them until links.next is null
let nextLink = tokenBalanceInfoJson.links.next;
while (nextLink !== null) {
const nextTokenBalanceInfo = await fetch(`${this.url}${nextLink}`, { method: "GET" });
const nextTokenBalanceInfoJson = await nextTokenBalanceInfo.json();
tokenBalances.push(...nextTokenBalanceInfoJson.tokens);
nextLink = nextTokenBalanceInfoJson.links.next;
}
return tokenBalances;
}
2.2 Query Token Information by Token ID
In the previous step we wrote code to obtain the current token balance of an account. Next we will retieve the type of token (Non-Fungible or Fungible), decimal precision, token name and symbol.
Open src/services/wallets/mirrorNodeClient.ts
and paste the interface outside of and above the MirrorNodeClient
class.
export interface MirrorNodeTokenInfo {
type: 'FUNGIBLE_COMMON' | 'NON_FUNGIBLE_UNIQUE',
decimals: string,
name: string,
symbol: string
token_id: string,
}
Paste the below HTTP GET request outside of and below the getAccountTokenBalances
function in the src/services/wallets/mirrorNodeClient.ts
file.
// Purpose: get token info for a token
// Returns: a MirrorNodeTokenInfo
async getTokenInfo(tokenId: string) {
const tokenInfo = await fetch(`${this.url}/api/v1/tokens/${tokenId}`, { method: "GET" });
const tokenInfoJson = await tokenInfo.json() as MirrorNodeTokenInfo;
return tokenInfoJson;
}
2.3 Query Account NFT Information by AccountID
In the previous step we wrote code to obtain the token details (token type, decimals, name, and symbol). Next we will retrieve the NFT serial numbers that are owned.
Open src/services/wallets/mirrorNodeClient.ts
and paste the interface outside of and above the MirrorNodeClient
class.
export interface MirrorNodeNftInfo {
token_id: string,
serial_number: number,
}
Paste the below HTTP GET request outside of and below the getTokenInfo
function in the src/services/wallets/mirrorNodeClient.ts
file.
// Purpose: get NFT Infor for an account
// Returns: an array of NFTInfo
async getNftInfo(accountId: AccountId) {
const nftInfo = await fetch(`${this.url}/api/v1/accounts/${accountId}/nfts?limit=100`, { method: "GET" });
const nftInfoJson = await nftInfo.json();
const nftInfos = [...nftInfoJson.nfts] as MirrorNodeNftInfo[];
// because the mirror node API paginates results, we need to check if there are more results
// if links.next is not null, then there are more results and we need to fetch them until links.next is null
let nextLink = nftInfoJson.links.next;
while (nextLink !== null) {
const nextNftInfo = await fetch(`${this.url}${nextLink}`, { method: "GET" });
const nextNftInfoJson = await nextNftInfo.json();
nftInfos.push(...nextNftInfoJson.nfts);
nextLink = nextNftInfoJson.links.next;
}
return nftInfos;
}
2.4 Combine Account Token Balances and Token Information via Data Aggregation
We need to combine all of our HTTP response data in order to display our available tokens in our DApp.
Open src/services/wallets/mirrorNodeClient.ts
and paste the interface outside of and above the MirrorNodeClient
class.
export interface MirrorNodeAccountTokenBalanceWithInfo extends MirrorNodeAccountTokenBalance {
info: MirrorNodeTokenInfo,
nftSerialNumbers?: number[],
}
Paste the function outside of and below the getNftInfo
function in the src/services/wallets/mirrorNodeClient.ts
file.
// Purpose: get token balances for an account with token info in order to display token balance, token type, decimals, etc.
// Returns: an array of MirrorNodeAccountTokenBalanceWithInfo
async getAccountTokenBalancesWithTokenInfo(accountId: AccountId): Promise<MirrorNodeAccountTokenBalanceWithInfo[]> {
//1. Retrieve all token balances in the account
const tokens = await this.getAccountTokenBalances(accountId);
//2. Create a map of token IDs to token info and fetch token info for each token
const tokenInfos = new Map<string, MirrorNodeTokenInfo>();
for (const token of tokens) {
const tokenInfo = await this.getTokenInfo(token.token_id);
tokenInfos.set(tokenInfo.token_id, tokenInfo);
}
//3. Fetch all NFT info in account
const nftInfos = await this.getNftInfo(accountId);
//4. Create a map of token Ids to arrays of serial numbers
const tokenIdToSerialNumbers = new Map<string, number[]>();
for (const nftInfo of nftInfos) {
const tokenId = nftInfo.token_id;
const serialNumber = nftInfo.serial_number;
// if we haven't seen this token_id before, create a new array with the serial number
if (!tokenIdToSerialNumbers.has(tokenId)) {
tokenIdToSerialNumbers.set(tokenId, [serialNumber]);
} else {
// if we have seen this token_id before, add the serial number to the array
tokenIdToSerialNumbers.get(tokenId)!.push(serialNumber);
}
}
//5. Combine token balances, token info, and NFT info and return
return tokens.map(token => {
return {
...token,
info: tokenInfos.get(token.token_id)!,
nftSerialNumbers: tokenIdToSerialNumbers.get(token.token_id)
}
});
}
2.5 Add Token Association Support
Before a user can receive a new token, they must associate with it. This association helps protect users from receiving unwanted tokens.
Open src/services/wallets/mirrorNodeClient.ts
and paste the function below the getAccountTokenBalancesWithTokenInfo
function.
// Purpose: check if an account is associated with a token
// Returns: true if the account is associated with the token, false otherwise
async isAssociated(accountId: AccountId, tokenId: string) {
const accountTokenBalance = await this.getAccountTokenBalances(accountId);
return accountTokenBalance.some(token => token.token_id === tokenId);
}
3. Adding in the User Interface
In this step, we'll copy and paste the home.tsx file, which contains all the necessary code for adding UI components that enable token transfers and association with a token.
Open src/pages/Home.tsx
and replace the existing code by pasting the below code:
4. Testing DApp Functionality
The application is ready to be started and tested. You will be testing:
4.1 Test Setup
You'll be creating four Hedera Testnet accounts, each with a balance of 10 HBAR. Two of these accounts will come pre-loaded with their own fungible tokens, and four accounts will come pre-loaded with their own non-fungible tokens (NFTs).
Open a new terminal window and create a new directory and change into that directory
mkdir hedera-test-accounts && cd hedera-test-accounts
Open hedera-test-accounts
folder in a new visual studio code window.
Create a new file and name it .env
with the following contents. Remember to enter your account ID and your private key.
MY_ACCOUNT_ID=<enter your account id>
MY_PRIVATE_KEY=<enter your DER private key>
Within the hedera-test-accounts
home directory, execute the following command in the terminal,
npx github:/hedera-dev/hedera-create-account-and-token-helper
Keep this terminal open for the remainder of the tutorial, as you will refer back to it.
4.2 Import Sender and Receiver accounts
Import the sender and receiver accounts that were just outputted into your preferred wallet application. (MetaMask, HashPack, Blade, or Kabila)
For assistance on how to import a Hedera account into MetaMask refer to our documentation here.
Rename your imported accounts within your preferred wallet to keep track which is the sender and receiver account.
4.3 Start the DApp
Navigate back to your application in Visual Studio Code, and in the terminal, run the following command
npm run start

4.4 Connect to DApp as the Receiver
Click the Connect Wallet
button in the upper right and select MetaMask and select the Sender account.



4.5 Associate Receiver Account with Sender Account NFT
Open the output of the test accounts you created earlier and copy the ecdsaWithAlias
Sender's account NftTokenId
Paste the NftTokenId
in the DApps associate token textbox and click the button Associate

MetaMask will prompt you to sign the transaction. If the extension does not automatically open, you will need to manually click on the MetaMask extension.

Confirm the transaction
The react template uses the Hashio JSON RPC Relay URL to work with MetaMask. If you are experiencing degraded performance, follow this guide to switch to Arkhia or set up your own JSON RPC Relay. Edit the src/config/networks.ts
with the new JSON RPC Relay URL.
4.6 Transfer NFT to Receiver Account
Disconnect as the Receiver account and reconnect with the Sender account. To do this, open the MetaMask extension, click on the three dots in the upper right, select "Connected Sites," and then disconnect the Receiver account. All other wallets disconnect by clicking on your account ID in the upper right of the DApp homepage.
Connect to the DApp as the Sender Account.
As the Sender,
Select from available tokens the HederaNFT
Select the NFT with serial number 5 from the drop-down menu.
Enter the account ID or EVM address of the Receiver account.
Click the "send" button.
Sign the transaction on MetaMask to complete the transfer of the NFT from the Sender to the receiver account.

4.7 Verify Receiver Account Receieved the NFT
Disconnect as the Sender account and reconnect as the Receiver account.
Check the dropdown menu and ensure the Receiver account has NFT serial number 5.

Try with HashPack, Blade or Kabila
Optionally, import your accounts into any of the above Hedera native wallets and test out transferring more tokens.
Complete
🎉 Congratulations! You have successfully walked through creating a Hedera DApp that transfers HTS tokens using MetaMask, HashPack, Blade, or Kabila.
You have learned how to:
Last updated
Was this helpful?