Blockchain Development Tips

How to Integrate Web3 wallet into ReactJS

Arnish Gupta
4 min readJun 27, 2022

A complete guide for Web3 integration and connect smart contract methods.

Hello Everyone, What we are going to learn today is a kind of elevator that connects the Html world to the Blockchain world. So before starting there is some points that we need to understand.

  1. Web3 Wallet is basically a decentralised wallet that maintain your balance and private key for a signature (Authentication).
  2. We can use these popular Web3 Wallets:
  • Metamask
  • Coinbase Wallet
  • Binance Wallet
  • Bitkeep Wallet
  • Any Wallet that support Wallet Connect Functionality.
Photo by Lautaro Andreani on Unsplash

We will learn to integrate the below points :

  1. Connect Web3 wallet and fetch balance.
  2. Transfer Native currency (ETH/BNB/MATIC).
  3. Interact with smart contract and call Read/Write methods.
  4. Listen smart contract events.

Note: I am assuming that you have good knowledge of ReactJS and basic fundamentals of blockchain. For more information about smart contract you can learn from this article.

We create the simple ReactJS project with this command

npx create-react-app sample-web3

It will look like this:

  • Smart Contract: We create a smart contract on Rinkeby with a variable and getter, setter and an event for emit after variable changed.

So our stage is ready to perform. We use the ethers.js library to connect blockchain services with ReactJS.

sudo npm install ethers

Connect Web3 wallet and fetch balance

First, we have to check whether the injected Web3 is enabled

const { ethereum } = window;if (!ethereum) {console.log("Make sure you have Metamask installed!");return;} else {console.log("Wallet exists! We're ready to go!")}

For request to connect the wallet


const accounts = await ethereum.request({ method: ‘eth_accounts’ });
if (accounts.length !== 0) {const account = accounts[0];console.log(“Connected Account: “, account);

For fetch the balance:

const network = ‘rinkeby’ // use rinkeby testnetconst provider = ethers.getDefaultProvider(network)provider.getBalance(account).then((balance) => {// convert a currency unit from wei to etherconst balanceInEth = ethers.utils.formatEther(balance)console.log(`${balanceInEth} ETH`)})

Transfer Native currency (ETH/BNB/MATIC)

We need sender’s private key for transfer the currency and we get the transactionHash that we can check it on the relative explorer.

const network = ‘rinkeby’ // use rinkeby testnetlet provider = ethers.getDefaultProvider(network)let privateKey = '## private key' // Sender private key:// wallet instance
let wallet = new ethers.Wallet(privateKey, provider)
let receiverAddress = '0xXXXXXXXXXXXX'// Ether amount to send
let amountInEther = 'X.XXX'
// Create a transaction object
let tx = {
to: receiverAddress,
// Convert currency unit from ether to wei
value: ethers.utils.parseEther(amountInEther)
}
// Send a transaction
wallet.sendTransaction(tx)
.then((txObj) => {
console.log('txHash', txObj.hash)// A transaction result can be checked in a rinkeby with a transaction hash which can be obtained here.
})

Interact with Smart Contract and Call Read/Write methods.

  • First we have to create the instance.
  • Get the ABI from explorer (go to contract tab) like the below image.
const network = 'rinkeby' // use rinkeby testnetconst contractAddress = "0xXXXXXXXXXXXXXXXXXXXXX";const abi = [{ "inputs": [], "stateMutabil............}];let provider = ethers.getDefaultProvider(network)
const erc20 = new ethers.Contract(contractAddress, abi, provider)
  • Read the public method.
const nameInf = await erc20.name()console.log(“Name Field: “, nameInf)
  • Write the public method (For write method we will create a instance with a signer private key)
const network = 'rinkeby' // use rinkeby testnetlet provider = ethers.getDefaultProvider(network)const privateKey = “########################################”;let wallet = new ethers.Wallet(privateKey, provider)const learnToken = new ethers.Contract(contractAddress, abi, wallet)
  • Call the write method
const createReceipt = await learnToken.setName(name);await createReceipt.wait();console.log(`Tx successful with hash: ${createReceipt.hash}`);

Listen smart contract events

  • Smart contract has events for broadcasting information. For listen the events we use on keyword.
learnToken.on("NameChanged", (newName) => {   console.log("New Name: ", newName);});

Finally We have done all the things. I’m sharing the complete App.js file with a complete example.

If you have any question, you can ask here. I will be very happy to help you.

let’s enjoy this road together. Best of luck for your blockchain journey.

Happy Learning… !!

--

--

Arnish Gupta

Learn Blockchain with me every Monday at 9AM (GMT+5:30).