Connect MetaMaskWallet to Frontend on Binance Smart Chain (Part 2)

Phyzixmusic
Hexmount
Published in
2 min readApr 4, 2021

In the last part of this guide, we covered the architecture of basic smart contracts and identified the different components users must navigate through in order to interact with our basic smart contracts. If you haven't seen the first part of this series, you can read through part 1 here:

In our React app’s src folder, create a file called ethereum.js and place the following code

import detectEthereumProvider from '@metamask/detect-provider';
import { ethers, Contract } from 'ethers';
import SimpleStorage from './contracts/SimpleStorage.json';

const getBlockchain = () =>
new Promise( async (resolve, reject) => {
let provider = await detectEthereumProvider();
if(provider) {
await provider.request({ method: 'eth_requestAccounts' });
const networkId = await provider.request({ method: 'net_version' })
provider = new ethers.providers.Web3Provider(provider);
const signer = provider.getSigner();
const simpleStorage = new Contract(
SimpleStorage.networks[networkId].address,
SimpleStorage.abi,
signer
);
resolve({simpleStorage});
return;
}
reject('Install Metamask');
});

export default getBlockchain;

We are export a getBlockchain function from this file, it is going to return a javascript object that points to our smart contract on the blockchain.

We use

let provider = await detectEthereumProvider()

to get the current network provider that the user’s browser is connected to. Remember that Metamask supports more than one network and for the sake of this guide, users must be using the live version of the Binance smart chain.

The user will then receive a pop-up to ask permission to allow our Dapp to read the user’s public address.

const signer = provider.getSigner();

We also import a JSON file here

import SimpleStorage from './contracts/SimpleStorage.json';

This is the JSON file produced by Truffle when you compile the smart contract, this is used as an interface for our contracts.

That's it! This is the extra logic we have to create, in the next and file part of this guide, we will look into utilizing the codebase above as part of our frontend.

--

--