When using Web3Modal to obtain user wallet addresses, it is important to understand that Web3Modal is a library enabling developers to connect to various blockchain wallets in a straightforward manner. Below are the basic steps to use Web3Modal for obtaining user wallet addresses:
Step 1: Install Web3Modal
First, you need to install Web3Modal in your project. This can be done using npm:
bashnpm install web3modal
Step 2: Import Dependencies
In your project, import Web3Modal along with a Web3 library (such as ethers.js or web3.js). Here, we use ethers.js as an example:
javascriptimport Web3Modal from "web3modal"; import { ethers } from "ethers";
Step 3: Initialize Web3Modal
Initialize the Web3Modal instance and configure the supported wallets (e.g., MetaMask, WalletConnect, etc.):
javascriptconst providerOptions = { /* Configure different wallet options */ }; const web3Modal = new Web3Modal({ network: "mainnet", // Optional network configuration, e.g., mainnet, ropsten, rinkeby, etc. cacheProvider: true, // Whether to cache the user's selected provider providerOptions // Provider options });
Step 4: Connect Wallet and Obtain Address
When the user initiates a wallet connection, call the connect method of Web3Modal to trigger the connection process:
javascriptasync function connectWallet() { try { const provider = await web3Modal.connect(); // Trigger wallet connection const web3Provider = new ethers.providers.Web3Provider(provider); const signer = web3Provider.getSigner(); const address = await signer.getAddress(); console.log("Connected address:", address); return address; } catch (error) { console.error("Could not get a wallet connection", error); return null; } }
Example
Let's illustrate this with a simple example. Suppose you are working on a React application where you need to connect a wallet and display the wallet address when the user clicks a button:
javascriptimport React from 'react'; import Web3Modal from 'web3modal'; import { ethers } from 'ethers'; const web3Modal = new Web3Modal({ network: "mainnet", // Optional cacheProvider: true, }); function App() { const [address, setAddress] = React.useState(""); async function handleConnect() { const provider = await web3Modal.connect(); const web3Provider = new ethers.providers.Web3Provider(provider); const signer = web3Provider.getSigner(); const addr = await signer.getAddress(); setAddress(addr); } return ( <div> <button onClick={handleConnect}>Connect Wallet</button> {address && <p>Connected Address: {address}</p>} </div> ); } export default App;
In this example, when the user clicks the "Connect Wallet" button, Web3Modal will prompt a UI for the user to select and connect a wallet. Once the wallet is successfully connected, we can retrieve the user's wallet address using ethers.js and display it.