Skip to main content

Web3Modal

This tutorial is a step-by-step guide on how to integrate multiple wallets such as 3S Wallet, Metamask, and Wallet Connect into your dapp using the web3modal V1 library.

To test a running version click here.

web3modal

Image 1: Example of a custom modal built with the web3modal library

info

A working React application, set up using npx create-react-app app-name or similar

Setup Web3-react and Wallet Provider Options

Step 1: Install Web3Modal and an Ethereum library

Install your preferred Ethereum library for interacting with the blockchain. This tutorial will use ethers.js.

npm install ethers
npm install web3modal

Step 2: Instantiate Web3Modal with wallet provider options

Install the wallet providers of your choice. Here we install 3S Wallet and Wallet Connect.

npm install @walletconnect/web3-provider
npm install @3swallet.js/providers

In your App.js file, import 3SWallet.js and WalletConnect, and instantiate the various provider options to integrate into your dapp. Each provider has its own set of required parameters to pass in, such as a fallback JSON RPC URL or default chain ID. By default, Web3Modal includes the browser injected wallet (e.g. Metamask).

import { Web3Provider } from "@3swallet.js/providers";
//import WalletConnect from "@walletconnect/web3-provider";

export const providerOptions = {
walletconnect: {
display: {
name: "3S Wallet",
logo: "https://cdn.bho.network/cms/3s_4b0df03d62.svg",
description: "Scan with 3S Wallet mobile app to connect"
},
package: Web3Provider,
options: {
infuraId: process.env.INFURA_KEY,
rpc: {
1: `https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`,
56: `https://bscrpc.com`
},
supportedChainIds: [1, 56]
}
}
};

Step 3: Instantiate web3modal

Then, instantiate Web3Modal by passing in the provider options.

import Web3Modal from "web3modal";

const web3Modal = new Web3Modal({
providerOptions // required
});

Establish a Connection to Wallet

To establish a connection to the user’s wallet, call the connect function from the Web3Modal instance. We recommend you to wrap this operation around an async function and store the retrieved library in your state to reuse throughout the app.

import { ethers } from 'ethers';
import { useState } from 'react';

function App() {

const [provider, setProvider] = useState();
const [library, setLibrary] = useState();

const connectWallet = async () => {
try {
const provider = await web3Modal.connect();
const library = new ethers.providers.Web3Provider(provider);
setProvider(provider);
setLibrary(library);
} catch (error) {
console.error(error);
}
};

return (
<div className="App">
<button onClick={connectWallet}>Connect Wallet</button>
</div>
);
}

You should now be able to connect to 3S Wallet and other wallets easily from your dapp.

For more details, read the example source code