Integrate Web3-Onboard into a dApp
Introduction
Leveraging a tool like Web3-Onboard, projects and developers may quickly integrate multiple wallets into their decentralized applications (dApps). With the help of Web3-Onboard, user onboarding has been simplified. Web3-Onboard does have different features, ranging from support for several wallets to the ability for users to connect their accounts to different chains or networks and receive real-time transaction notifications, et cetera.
In this guide, you will use Web3-Onboard library to integrate multiple wallets (such as Coinbase Wallet, Metamask, WalletConnect, etc.) into your dApp built on the Kaia Network.
Prerequisite
- A working react project (by executing
npx create-react-app project-name
) - Install the necessary wallets (Coinbase Wallet, Metamask).
- RPC Endpoint: you can get this from one of the supported endpoint providers.
- Test KAIA from Faucet: fund your account with sufficient KAIA.
Getting Started
Web3-Onboard as a chain-agnostic wallet library, supports all EVM-compatible networks and also provides the flexibility of adding new networks to the library. In this guide, we'll use Web3-Onboard to add the Kaia Mainnet and Kaia Testnet Kairos to our dApp. With that said, let’s get started integrating multi-wallet compatibility using Web3-Onboard into your dApp built on Kaia Network.
Setting up Onboard and Wallet Modules
Step 1: Install @web3-onboard/core
npm i @web3-onboard/core
Step 2: Import and Instantiate Wallet Modules
In this step, you can add as many wallets to be supported in your dApp using the wallet modules. But for this guide, you will add Coinbase Wallet, WalletConnect, Injected Wallets to your web3-Onboard implementation. Refer to this docs for a list of wallet modules that can be added to your dApp using Web3-Onboard.
npm install @web3-onboard/coinbase // Coinbase Walletnpm install @web3-onboard/walletconnect // WalletConnectnpm install @web3-onboard/injected-wallets // Used to connect to Metamask
In your App.js
file, instantiate the wallet modules to integrate with your dApp. Note that each module has its own unique options parameters to pass in, such as a fallback JSON RPC URL or default chain ID.
import coinbaseWalletModule from "@web3-onboard/coinbase";import walletConnectModule from "@web3-onboard/walletconnect";import injectedModule from "@web3-onboard/injected-wallets";const coinbaseWalletSdk = coinbaseWalletModule();const walletConnect = walletConnectModule();const injected = injectedModule();const modules = [coinbaseWalletSdk, walletConnect, injected];
Step 3: Install and import ethers
The Web3-Onboard provider can be used with libraries like ethers.js and web3.js. In this guide, we will use ethers.js to make Kaia blockchain calls like getting the user's account, fetch balance, sign transaction, send transaction, read from and write to the smart contract.
npm install --save ethers
In your App.js
file, import the ethers package like this:
import { ethers } from "ethers";
Step 4: Import and Setup Web3ReactProvider
In this step, you will instantiate Onboard with the created modules and a list of chains to be compatible with the library. Open up your App.js
file and paste the code below:
import Onboard from "@web3-onboard/core";const ETH_MAINNET_RPC_URL = `Paste ETH RPC URL`;const KAIA_MAINNET_URL = `Paste KAIA MAINNET URL`const KAIA_BAOBAB_URL = `Paste KAIA BAOBAB URL`const onboard = Onboard({ wallets: modules, // created in previous step chains: [ { id: "0x1", // chain ID must be in hexadecimal token: "ETH", namespace: "evm", label: "Ethereum Mainnet", rpcUrl: ETH_MAINNET_RPC_URL }, { id: "0x2019", // chain ID must be in hexadecimal token: "KAIA", namespace: "evm", label: "Kaia Mainnet", rpcUrl: KAIA_MAINNET_URL }, { id: "0x3e9", // chain ID must be in hexadecimel token: "KAIA", namespace: "evm", label: "Kaia Testnet", rpcUrl: KAIA_BAOBAB_URL }, // you can add as much supported chains as possible ], appMetadata: { name: "Kaia-web3-onboard-App", // change to your dApp name icon: "https://pbs.twimg.com/profile_images/1620693002149851137/GbBC5ZjI_400x400.jpg", // paste your icon logo: "https://pbs.twimg.com/profile_images/1620693002149851137/GbBC5ZjI_400x400.jpg", // paste your logo description: "Web3Onboard-Kaia", recommendedInjectedWallets: [ { name: "Coinbase", url: "https://wallet.coinbase.com/" }, { name: "MetaMask", url: "https://metamask.io" } ] }});
Setting up Utils function
In this guide, we will be making use of the utils functions such as truncateAddress()
and toHex()
. The truncateAddress()
function takes in a valid address and returns a more readable format of the address passed in. While the toHex()
function converts numbers to hexadecimal. The following steps below show how to set up and use the utils function in your project.
Step 1: Create a utils.js
file in the src
root folder.
Paste the following code in the newly created utils.js file.
export const truncateAddress = (address) => { if (!address) return "No Account"; const match = address.match( /^(0x[a-zA-Z0-9]{2})[a-zA-Z0-9]+([a-zA-Z0-9]{4})$/ ); if (!match) return address; return `${match[1]}…${match[2]}`; }; export const toHex = (num) => { const val = Number(num); return "0x" + val.toString(16); };
Step 2: Import the functions in your App.js
file.
import { truncateAddress, toHex } from "./utils";
Connecting Wallet
Inside your App function in your App.js
file, call the connectWallet()
method on the onboard instance to initiate the onboard popup modal.
function App() { const connectWallet = async () => { try { const wallets = await onboard.connectWallet(); } catch (error) { console.error(error); } }; return ( <div className="App"> <button onClick={connectWallet}>Connect Wallet</button> </div> );}
Once you click your Connect Wallet button, you should see a modal that allows you to seamlessly connect to Coinbase Wallet and other instantiated wallets from your dApp.
Disconnecting Wallet
Disconnecting a connected wallet can be achieved by calling the disconnectWallet()
method on the onboard instance along with the label of the user's primary wallet. Also, one good practice is to refresh the state to clear any previously stored connection data.
function App() { const connectWallet = async () => { try { const wallets = await onboard.connectWallet(); } catch (error) { console.error(error); } }; const disconnect = async () => { const [primaryWallet] = await onboard.state.get().wallets; if (primaryWallet) await onboard.disconnectWallet({ label: primaryWallet.label }); refreshState(); }; // refresh state const refreshState = () => { setAccount(""); setChainId(""); setProvider(); // make sure to add every other state declared here. }; return ( <div className="App"> <button onClick={connectWallet}>Connect Wallet</button> <button onClick={disconnect}>Disconnect</button> </div> );}