Unicorn Ultra
  • Welcome to unicorn ultra — let’s build the future
  • Getting Started
    • Introduction
    • Environment Setup
    • Create an Account
    • Transfer U2U
    • Query Ledger Data
  • Tutorials
    • Smart Contracts
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Create an HBAR Faucet App Using React and MetaMask
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Smart Contract Using Hardhat
      • Deploy a Subgraph Using The Graph and JSON-RPC
      • How to Set Up Foundry to Test Smart Contracts on Hedera
      • Deploy Smart Contracts on Hedera Using Truffle
    • Consensus
      • Submit Your First Message
      • Submit Message to Private Topic
      • Query Messages with Mirror Node
    • Tokens
      • Create and Transfer Your First NFT
      • Create and Transfer Your First Fungible Token
      • Create and Transfer an NFT using a Solidity Contract
      • Structure Your Token Metadata Using JSON Schema V2
    • More Tutorials
      • How to Auto-Create Hedera Accounts with HBAR and Token Transfers
      • How to Configure a Mirror Node and Query Data
      • How to Generate a Random Number on Hedera
      • Get Started with the Hedera Consensus Service Fabric Plugin
        • Virtual Environment Setup
      • Schedule Your First Transaction
      • How to Connect to Hedera Networks Over RPC
        • Configuring Hashio RPC endpoints
        • Configuring Arkhia RPC endpoints
        • Configuring Hedera JSON-RPC Relay endpoints
    • Demo Applications
    • Starter Projects
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • Reference Configuration
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Network Explorers and Tools
    • Release Notes
      • Hedera Services
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Scheduled Transaction
    • Smart Contracts
      • Hyperledger Besu EVM
      • Gas and Fees
      • Solidity Variables and Opcodes
      • Supported ERC Token Standards
      • Hedera Services Integration with Smart Contracts
      • JSON-RPC Relay
      • Hethers
      • Smart Contract Security
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
    • State and History
    • Mirror Nodes
      • Hedera Mirror Node
      • One Click Mirror Node Deployment
      • Run Your Own Mirror Node
        • Run Your Own Mirror Node with Google Cloud Storage (GCS)
        • Run Your Mirror Node with Amazon Web Services S3 (AWS)
      • Hedera ETL
  • SDKs & APIs
    • SDKs
      • Build Your Hedera Client
      • Set Up Your Local Network
      • Network Address Book
      • Keys
        • Generate a new key pair
        • Import an existing key
        • Create a key list
        • Create a threshold key
        • Generate a mnemonic phrase
        • Recover keys from a mnemonic phrase
      • HBAR
      • Specialized Types
      • Pseudorandom Number Generator
      • Transactions
        • Transaction ID
        • Modify transaction fields
        • Create an unsigned transaction
        • Manually sign a transaction
        • Submit a transaction
        • Sign a multisignature transaction
        • Get a transaction receipt
        • Get a transaction record
      • Schedule Transaction
        • Schedule ID
        • Create a scheduled transaction
        • Sign a scheduled transaction
        • Delete a scheduled transaction
        • Get schedule info
        • Network Response Messages
        • Schedule FAQ
      • Queries
      • General Network Response Messages
      • Accounts and HBAR
        • Create an account
        • Update an account
        • Transfer cryptocurrency
        • Approve an allowance
        • Delete an allowance
        • Delete an account
        • Get account balance
        • Get account info
        • Network Response Messages
      • Consensus Service
        • Create a topic
        • Update a topic
        • Submit a message
        • Delete a topic
        • Get topic messages
        • Get topic info
        • Network Response
      • Token Service
        • Token ID
        • NFT ID
        • Token types
        • Create a token
        • Custom token fees
        • Update a token
        • Update token custom fees
        • Transfer tokens
        • Delete a token
        • Mint a token
        • Burn a token
        • Freeze an account
        • Unfreeze an account
        • Enable KYC account flag
        • Disable KYC account flag
        • Associate tokens to an account
        • Dissociate tokens from an account
        • Pause a token
        • Unpause a token
        • Wipe a token
        • Atomic swaps
        • Get account token balance
        • Get token info
        • Get NFT info
        • Network Response Messages
      • File Service
        • Create a file
        • Append to a file
        • Update a file
        • Delete a file
        • Get file contents
        • Get file info
        • Network Response Messages
      • Smart Contract Service
        • Delegate Contract ID
        • Create a smart contract
        • Update a smart contract
        • Delete a smart contract
        • Call a smart contract function
        • Ethereum transaction
        • Get a smart contract function
        • Get smart contract bytecode
        • Get smart contract info
        • Hedera Service Solidity Libraries
        • Network Response Messages
      • Signature Provider
        • Provider
        • Signer
        • Wallet
        • Local Provider
    • REST API
    • Hedera Consensus Service gRPC API
    • Hedera APIs
      • Basic Types
        • AccountAmount
        • AccountID
        • ContractID
        • CryptoAllowance
        • CurrentAndNextFeeSchedule
        • FeeComponents
        • FeeData
        • FeeSchedule
        • FileID
        • Fraction
        • HederaFunctionality
        • Key
        • KeyList
        • NftAllowance
        • NftTransfer
        • NodeAddress
        • NodeAddressBook
        • RealmID
        • ScheduleID
        • SemanticVersion
        • ServicesConfigurationList
        • ServiceEndpoint
        • Setting
        • ShardID
        • Signature
        • SignatureList
        • SignatureMap
        • SignaturePair
        • SubType
        • TransferList
        • TransactionID
        • ThresholdKey
        • ThresholdSignature
        • TokenAllowance
        • TokenBalance
        • TokenBalances
        • TokenFreezeStatus
        • TokenPauseStatus
        • TokenID
        • TokenKycStatus
        • TokenRelationship
        • TokenTransferList
        • TokenType
        • TokenSupplyType
        • TopicID
        • TransactionFeeSchedule
      • Cryptocurrency Accounts
        • CryptoService
        • CryptApproveAllowance
        • CryptoDeleteAllowance
        • CryptoCreate
        • CryptoTransfer
        • CryptoUpdate
        • CryptoDelete
        • CryptoGetAccountBalance
        • CryptoGetAccountRecords
        • CryptoGetInfo
        • CryptoGetStakers
      • Consensus Service
        • Consensus Service
        • ConsensusCreateTopic
        • ConsensusUpdateTopic
        • ConsensusSubmitMessage
        • ConsensusDeleteTopic
        • ConsensusTopicInfo
        • ConsensusGetTopicInfo
      • Schedule Service
        • ScheduleService
        • SchedulableTransactionBody
        • ScheduleCreate
        • ScheduleDelete
        • ScheduleSign
        • ScheduleGetInfo
      • Token Service
        • TokenService
        • CustomFees
          • AssessedCustomFee
          • CustomFee
          • FractionalFee
          • FixedFee
          • RoyaltyFee
        • TokenCreate
        • TokenUpdate
        • TokenFeeScheduleUpdate
        • TokenDelete
        • TokenMint
        • TokenBurn
        • TokenFreezeAccount
        • TokenUnfreezeAccount
        • TokenGrantKyc
        • TokenRevokeKyc
        • TokenAssociate
        • TokenDissociate
        • TokenWipeAccount
        • TokenPause
        • TokenUnpause
        • TokenGetInfo
        • TokenGetNftInfo
        • TokenGetNftInfos
        • TokenGetAccountNftInfo
      • File Service
        • FileService
        • FileCreate
        • FileAppend
        • FileUpdate
        • FileDelete
        • FileGetContents
        • FileGetInfo
      • Smart Contracts
        • SmartContractService
        • ContractCall
        • ContractCallLocal
        • ContractCreate
        • ContractUpdate
        • ContractDelete
        • ContractGetByteCode
        • ContractGetInfo
        • ContractGetRecords
      • Miscellaneous
        • Duration
        • ExchangeRate
        • Freeze
        • FreezeType
        • GetByKey
        • GetBySolidityID
        • NetworkGetVersionInfo
        • NetworkService
        • Query
        • QueryHeader
        • Response
        • ResponseCode
        • ResponseHeader
        • SystemDelete
        • SystemUndelete
        • TimeStamp
        • Transaction
        • TransactionBody
        • TransactionContents
        • TransactionGetFastRecord
        • TransactionGetReceipt
        • TransactionGetRecord
        • TransactionReceipt
        • TransactionRecord
        • TransactionResponse
        • UncheckedSubmit
    • Deprecated
      • SDKs (V1)
        • Build your Hedera client
        • Set-up Your Local Network
        • Network address book
        • Keys
          • Generate a new key pair
          • Import an existing key
          • Create a key list
          • Create a threshold key
          • Generate a mnemonic phrase
          • Recover keys from a mnemonic phrase
        • Hbars
        • Specialized Types
        • Pseudorandom Number Generator
        • Transactions
          • Transaction ID
          • Modify transaction fields
          • Create an unsigned transaction
          • Manually sign a transaction
          • Submit a transaction
          • Sign a multisignature transaction
          • Get a transaction receipt
          • Get a transaction record
        • Scheduled Transaction
          • Schedule ID
          • Create a scheduled transaction
          • Sign a scheduled transaction
          • Delete a scheduled transaction
          • Get schedule info
          • Network Response Messages
          • Schedule FAQ
        • Queries
        • General Network Response Messages
        • Accounts and hbar
          • Create an account
          • Update an Account
          • Transfer cryptocurrency
          • Approve an allowance
          • Delete an allowance
          • Delete an account
          • Get account balance
          • Get account info
          • Network Response Messages
        • Consensus Service
          • Create a topic
          • Update a topic
          • Submit a message
          • Delete a topic
          • Get topic messages
          • Get topic info
        • Token Service
          • Token ID
          • NFT ID
          • Token types
          • Create a token
          • Custom token fees
          • Update a token
          • Update token custom fees
          • Transfer tokens
          • Delete a token
          • Mint a token
          • Burn a token
          • Freeze an account
          • Unfreeze an account
          • Enable KYC account flag
          • Disable KYC account flag
          • Associate tokens to an account
          • Dissociate tokens from an account
          • Pause a token
          • Unpause a token
          • Wipe a token
          • Atomic swaps
          • Get account token balance
          • Get token info
          • Get NFT info
          • Network Response Messages
        • File Service
          • Create a file
          • Append to a file
          • Update a file
          • Delete a file
          • Get file contents
          • Get file info
          • Network Response Messages
  • Support & Community
    • Glossary
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Meetups
    • Contributing Guide
    • Brand Guidelines
    • Status Page
Powered by GitBook
On this page
  • Prerequisites
  • Create React App
  • Configure MetaMask with Hedera Testnet Network
  • Connect Our dApp to MetaMask and Retrieve Wallet Address
  • Install Hedera JS SDK and Create Your Client
  • Install Dependencies
  • Create Your Client
  • Build Your TransferTransaction
  • Send U2U to MetaMask Wallet
  • Configure State Management
  • Add Functionality to the NavBar Button
  • Add Send HBAR Button
  • Summary
  1. Tutorials
  2. Smart Contracts

Create an HBAR Faucet App Using React and MetaMask

PreviousSend and Receive HBAR Using Solidity Smart ContractsNextDeploy By Leveraging Ethereum Developer Tools On Hedera

Last updated 1 year ago

Enabling the opportunity to connect to a decentralized application (dApp) with different wallets provides more control to the user. Recently, 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 , 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.

Prerequisites

  • Create a Hedera Testnet account .

  • Install the .

  • Basic understanding of and .

  • Set up your environment and create your client .

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.

Project Repos

The complete TypeScript project can be found on GitHub .

The complete JavaScript project can be found on GitHub .

Create React App

Open your terminal and run the following command to create a React app that utilizes TypeScript and Material UI.

npx create-react-app <app-name> --template hedera-theme

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:

├── node_modules
├── publicLA
├── src
├── .gitignore
├── package-lock.json
├── package.json
├── README.md
└── tsconfig.json

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:

src
├── assets
├── components
├── App.tsx
├── AppRouter.tsx
├── Home.tsx
├── index.tsx
├── react-app-env.ts

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:

src
├── assets
├── components
├── services
	├── metamaskServices.ts
├── App.tsx
├── AppRouter.tsx
├── Home.tsx
├── index.tsx
├── react-app-env.ts

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.

Let's begin!

In our metamaskService.ts file, create a function named switchToHederaNetwork.

export const switchToHederaNetwork = async (ethereum: any) => {
  try {
    await ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x128' }] // chainId must be in hexadecimal numbers
    });
  } catch (error: any) {
    if (error.code === 4902) {
      try {
        await ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [
            {
              chainName: 'Hedera Testnet',
              chainId: '0x128',
              nativeCurrency: {
                name: 'HBAR',
                symbol: 'HBAR',
                decimals: 18
              },
              rpcUrls: ['https://testnet.hashio.io/api']
            },
          ],
        });
      } catch (addError) {
        console.error(addError);
      }
    }
    console.error(error);
  }
}

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().

// returns a list of accounts
// otherwise empty array
export const connectToMetamask = async () => {
  const { ethereum } = window as any;
  // keep track of accounts returned
  let accounts: string[] = []
  if (!ethereum) {
    throw new Error("Metamask is not installed! Go install the extension!");
  }
  
  switchToHederaNetwork(ethereum);
  
  accounts = await ethereum.request({
    method: 'eth_requestAccounts',
  });
  return accounts;
}

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 Hedera JS SDK and Create Your Client

We’ve written the code to connect our application to MetaMask. Now it’s time to send HBAR to our MetaMask wallet.

Install Dependencies

Install the Hedera JavaScript SDK and dotenv by running the following command in the project root directory:

npm install --save @hashgraph/sdk dotenv

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:

REACT_APP_MY_ACCOUNT_ID=
REACT_APP_MY_PRIVATE_KEY=

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.

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.

export default function Home() {
  // If we weren't able to grab it, we should throw a new error
  if (!process.env.REACT_APP_MY_ACCOUNT_ID || !process.env.REACT_APP_MY_PRIVATE_KEY) {
    throw new Error("Environment variables REACT_APP_MY_ACCOUNT_ID and REACT_APP_MY_PRIVATE_KEY must be present");
  }

  // create your client
  const myAccountId = AccountId.fromString(process.env.REACT_APP_MY_ACCOUNT_ID);
  const myPrivateKey = PrivateKey.fromString(process.env.REACT_APP_MY_PRIVATE_KEY);

  const client = Client.forTestnet();
  client.setOperator(myAccountId, myPrivateKey);

  return (
    <Stack 
      spacing={4}
      sx={{alignItems: 'center'}}
    >
      <Typography
        variant="h4"
        color="white"
      >
        Let's buidl a dApp on Hedera
      </Typography>
    </Stack>
  )
}

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.

import { AccountId, Client, PrivateKey, TransactionReceiptQuery, TransferTransaction } from "@hashgraph/sdk"

export const sendHbar = async (client:Client, fromAddress: AccountId | string, toAddress: AccountId | string, amount: number, operatorPrivateKey: PrivateKey) => {
  const transferHbarTransaction = new TransferTransaction()
    .addHbarTransfer(fromAddress, -amount)
    .addHbarTransfer(toAddress, amount)
    .freezeWith(client);

  const transferHbarTransactionSigned = await transferHbarTransaction.sign(operatorPrivateKey);
  const transferHbarTransactionResponse = await transferHbarTransactionSigned.execute(client);

  // Get the child receipt or child record to return the Hedera Account ID for the new account that was created
  const transactionReceipt = await new TransactionReceiptQuery()
    .setTransactionId(transferHbarTransactionResponse.transactionId)
    .setIncludeChildren(true)
    .execute(client);

  const childReceipt = transactionReceipt.children[0];

  if(!childReceipt || childReceipt.accountId === null) {
    console.warn(`No account id was found in child receipt. Child Receipt: ${JSON.stringify(childReceipt, null, 4)}`);
    return;
  }

   const newAccountId = childReceipt.accountId.toString();
   console.log(`Account ID of the newly created account: ${newAccountId}`);
}

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.

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 U2U 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

Let's edit our src/contexts/GlobalAppContext.tsx file, which came with our template, to look like this:

import { createContext, ReactNode, useState } from "react";

const defaultValue = {
  metamaskAccountAddress: '',
  setMetamaskAccountAddress: (newValue: string) => { },
}

export const GlobalAppContext = createContext(defaultValue)

export const GlobalAppContextProvider = (props: { children: ReactNode | undefined }) => {
  const [metamaskAccountAddress, setMetamaskAccountAddress] = useState('')

  return (
    <GlobalAppContext.Provider
      value={{
        metamaskAccountAddress,
        setMetamaskAccountAddress
      }}
    >
      {props.children}
    </GlobalAppContext.Provider>
  )
}

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:

export default function NavBar() {
  // use the GlobalAppContext to keep track of the metamask account connection
  const { metamaskAccountAddress, setMetamaskAccountAddress } = useContext(GlobalAppContext);

Next, we will create a new function to connect to MetaMask and store the wallet address in the GlobalAppContext.

const retrieveWalletAddress = async () => {
	const addresses = await connectToMetamask();
	if (addresses) {
      // grab the first wallet address
      setMetamaskAccountAddress(addresses[0]);
      console.log(addresses[0]);
    }
  }

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:

<Button
	variant='contained'
	color='secondary'
	sx={{
		ml: 'auto'
	}}
	onClick={retrieveWalletAddress}
>
	{metamaskAccountAddress === "" ?
		"Connect to MetaMask" :
		`Connected to: ${metamaskAccountAddress.substring(0, 8)}...`}
</Button>

Add Send HBAR Button

In the Home.tsx file, we will call our global context to gain access to our metamaskAccountAddress state variable.

export default function Home() {
  const { metamaskAccountAddress } = useContext(GlobalAppContext);

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.

onClick={() => {
	sendHbar(client, myAccountId, AccountId.fromEvmAddress(0, 0, metamaskAccountAddress), 7, myPrivateKey)
}}

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:

<Stack 
  spacing={4}
  sx={{alignItems: 'center'}}
>
	<Typography
  		variant="h4"
  		color="white"
	>
  	  Let's buidl a dApp on Hedera
	</Typography>
	<Button
  	  variant="contained"
  	  color="secondary"
  	  onClick={() => {
    	sendHbar(client, myAccountId, AccountId.fromEvmAddress(0, 0, metamaskAccountAddress), 7, myPrivateKey)
  	  }}
	>
  	  Transfer HBAR to MetaMask Account
	</Button>
</Stack>

We’re ready to run our application! Open a terminal In the root directory of the project and run:

npm run start

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

Congratulations! 🎉 You successfully followed the tutorial to create an HBAR faucet for MetaMask and a Hedera React application that integrates with MetaMask!

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.

Feel free to reach out if you have any questions:

If you have not already installed the MetaMask Chrome extension, please install it .

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 (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 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 , which comes from , the SwirldsLabs-hosted version of the .

Note: If you need to create a Hedera Testnet account, visit and register to receive 10,000 test HBAR.

This function builds a 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.

When a transaction is executed, the result is of type . Use the transaction id from the TransactionResponse in a to get a , including children transactions.

You can learn and read more about on our documentation site.

React has a feature called 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.

here
Browser Object Model
https://testnet.hashio.io/api
Hashio
JSON-RPC Relay
portal.hedera.com
TransferTransaction
TransactionResponse
TransactionReceiptQuery
TransactionReceipt
parent and child transactions
Context
HIP-583
HIP-32
here
MetaMask Chrome extension
TypeScript
React
here
here
here

Writer: Abi, DevRel Engineer

Editor: Krystal, Technical Writer

1.

2.

3.

4.

5.

6.

|

|

GitHub
LinkedIn
GitHub
Twitter
PREREQUISITES
CREATE REACT APP
CONFIGURE METAMASK
CONNECT METAMASK
SEND HBAR
PROJECT REPOS