Ethereum Developer Tooling for Creating Better Web3 Dapps

Blocknative Ethereum Web3

How to connect wallets and add real-time transaction notifications and customizable alerts to any front-end framework with Web3 Onboard

Are you building a dapp and looking for an easy and reliable web3 developer tooling to add a connect wallet button, support multiple accounts, and push transaction notifications to your users? With Web3 Onboard’s Core package, any developer can quickly set up their dapp to connect EVM (Ethereum Virtual Machine) compatible wallets, make transactions and sign contracts on any front-end framework or Javascript code base. Web3 Onboard also allows for a full range of customizations, styling and theming that makes the process of onboarding users look and feel natural and native in any dapp (decentralized application) environment.

This article we will cover the Web3 Onboard Core package and the API that is exposed. We will cover:

  • How to add a “connect wallet” button to your dapp
  • How to connect multiple wallets and accounts on your dapp
  • How to send transactions from your dapp
  • How to add real-time transaction notifications to your dapp so users can monitor their transaction through the mempool
  • How to add customizable alerts to your dapp
  • How to add pre-flight notifications (i.e. waiting for confirmation, insufficient funds, etc) to your dapp

The best part about the Web3 Onboard Core package is it is completely framework agnostic meaning it can be used within any front-end Javascript framework (Svelte, React, Next, Angular, Vue, etc), Typescript or Vanilla JS application. If you prefer to use React, Web3 Onboard has a React Hooks package or, if you are a Vue developer, check out the Vue Package.

In this article, we will use Svelte as our front-end framework but the same API usage and patterns can be used in any front-end Javascript library as the Core package is framework agnostic.

Accept injected wallets on your dapp

Injected wallets are wallets that connect to users' browsers, such as Metamask or Coinbase Wallet. You will most likely want to add this ability to your dapp. With this module, Injected Wallets are automatically detected on both desktop or within the specified wallet’s mobile app by Web3 Onboard. Full documentation for injected-wallets can be found in our official docs here.

To start accepting injected wallets, let's get started by installing a few packages using yarn or npm.

**NPM**
`npm i @web3-onboard/core @web3-onboard/injected-wallets ethers`
 
**Yarn**
`yarn add @web3-onboard/core @web3-onboard/injected-wallets ethers`

Initializing Web3 Onboard

Next we will initialize Web3-Onboard using the `Onboard` function provided by the @web3-onboard/core package. This can be done in a service file or directly in the entry file of your project. For this example we are using Svelte so we will have the initialization code in the App.svelte file.

For this example we will only add the Ethereum Mainnet and Rinkeby Testnet chains but any EVM chain can be added to the chains array (Polygon, BNB - Binance, Fantom, Arbitrum, Optimism, etc.).

To get started we will execute the `injectedModule()` function that we get from @web3-onboard/injected-wallet which will initialize the module and will allow Web3 Onboard to look for injected wallets on page load or button click. If we wanted to expand on the wallets accepted by your dapp Web3 Onboard supports many hardware and SDK wallets as well which can be added in the same way. See a full list here.

**Note - With injected wallets only wallets that are installed on the browser or used within the specified wallet’s mobile app will be displayed.

Next we will want to head to https://infura.io/ and sign up for a free Infura API key. This will allow us to retrieve balances and make RPC calls.

Full documentation around initializing Web3 Onboard can be found here.

import Onboard from '@web3-onboard/core'
import injectedModule from '@web3-onboard/injected-wallets'
 
const injected = injectedModule()
 
const infuraKey = ''
 
// initialize Onboard
const onboard = Onboard({
 wallets: [injected],
 chains: [
   {
     id: '0x1',
     token: 'ETH',
     label: 'Ethereum',
     rpcUrl: 'https://mainnet.infura.io/v3/${infuraKey}'
   },
   {
     id: '0x4',
     token: 'rETH',
     label: 'Rinkeby',
     rpcUrl: 'https://rinkeby.infura.io/v3/${infuraKey}'
   }
 ]
})

That’s it for initializing! Now let’s connect a wallet!

How to create a Connect Wallet button on your dapp

Now that Web3 Onboard is initialized and set up to look for and connect to injected wallets we can add code to connect wallets and make the wallet’s information available to the dapp. For this we will use the `connectWallet()` function on the initialized onboard object.

async function connectWallet() {
 const wallets = await onboard.connectWallet()
 console.log(wallets)
}
 
connectWallet()


<script>
 import Onboard from '@web3-onboard/core'
 import injectedModule from '@web3-onboard/injected-wallets'
 
 const injected = injectedModule()
 
const infuraKey = ''
 
 const onboard = Onboard({
   wallets: [
     injected
   ],
   chains: [
     {
       id: '0x1',
       token: 'ETH',
       label: 'Ethereum',
       rpcUrl: 'https://mainnet.infura.io/v3/${infuraKey}'
     },
     {
       id: 4,
       token: 'rETH',
       label: 'Rinkeby',
       rpcUrl: 'https://rinkeby.infura.io/v3/${infuraKey}'
     }
   ]
 })
 
</script>
 
<style>
 button {
   width: 14rem;
   margin: 8px;
 }
</style>
 
<main>
 <button on:click={() => onboard.connectWallet()}>Connect Wallet</button>
</main>

With this code we should have a very simple webpage with a button that looks like this:

basic-connect-wallet-buttonTo connect a wallet the user will need an extension wallet downloaded and installed on their browser. For more information on customizing this part of the onboarding experience checkout the section Add a custom message to your dapp if a user is not using a supported wallet in my other article. The rest of the article will assume you have at least one browser extension wallet installed and understand the process of adding wallet extension to your browser. For the purposes of this article I have installed MetaMask, Binance Chain Wallet and Coinbase wallet for demonstration purposes.

Verify by connecting a wallet

To verify that your dapp is able to connect to injected wallets we will assume the user has an injected wallet installed (see above for more info on customizing this part of the experience). After clicking Connect we will see the following:

example-wallets

After clicking the MetaMask button we will be asked by the wallet if we can connect to the dapp, which we will confirm.

**Note - Web3 Onboard allows users to connect multiple accounts from multiple wallets. At this step the user must select all accounts they want to connect through the “Connect With MetaMask” confirmation. There is no programmatic way to change the selection after a user has connected aside from the user manually revoking site access from the connected sites through the wallet and re-connecting to the application.

metamask-wallet-balances

After confirming the selected accounts in the wallet we will see:

metamask-connection

And then, boom! We have a wallet connected!

metamask-connected-with-balanceIn the upper corner of your dapp you will see the Web3 Onboard Account Center component. This is enabled by default and gives the user more information on and ways to interact with their connected wallets. Upon clicking the Account Center you will see an expanded Account Center view with options to change chains, connect another wallet, disconnect all wallets and more dapp info. Learn more about the Account Center.

Without a DApp icon or logo added to the Web3 Onboard initialization `appMetaData ` object, Onboard will default to showing a question mark in the connection successful section and Account Center and will default to showing a Blocknative logo in the left panel of the Onboard connect modal. To customize these to fit your DApp add your icons and logo to the `appMetaData` property within the initialization.

For the remainder of this article we will add the `appMetaData` property to the W3O initialization along with a Blocknative icon.

For more information on customizing the look and feel of Web3 Onboard through the `appMetaData` property please see our official documentation here.

How to connect multiple wallets or accounts to your dapp

Now that we have connected a wallet, we can make it easy for users to connect a second wallet.

To do this let's add the stream from the web3-onboard state and select ‘wallets’.

**Note - When using streams be sure to `unsubscribe` from the stream when updates are no longer needed to avoid memory leaks!

// Subscribe to wallet updates
 const wallets$ = onboard.state.select('wallets')
 const { unsubscribe } = wallets$.subscribe(update =>
   console.log('wallets update: ', update)
 )
 
 // unsubscribe when updates are no longer needed
 onDestroy(unsubscribe)

Let's also update the code to conditionally render a new button if a wallet is already connected. Along with more information on the wallet connected (balance/token, ENS if it exists, address and wallet icon) and a disconnect button.

<script>
 import Onboard from '@web3-onboard/core'
 import injectedModule from '@web3-onboard/injected-wallets'
 import { onDestroy } from 'svelte'
 
 import blocknativeIcon from './blocknative-icon'
 import blocknativeLogo from './blocknative-logo'
 
 const injected = injectedModule()
 
 const onboard = Onboard({
   wallets: [injected],
   chains: [
     {
       id: '0x1',
       token: 'ETH',
       label: 'Ethereum',
       rpcUrl: 'https://mainnet.infura.io/v3/17c1e1500e384acfb6a72c5d2e67742e'
     },
     {
       id: 4,
       token: 'rETH',
       label: 'Rinkeby',
       rpcUrl: 'https://rinkeby.infura.io/v3/17c1e1500e384acfb6a72c5d2e67742e'
     }
   ],
   appMetadata: {
     name: 'Blocknative',
     icon: blocknativeIcon,
     logo: blocknativeLogo,
     description: 'Demo app for Onboard V2',
     recommendedInjectedWallets: [
       { name: 'MetaMask', url: 'https://metamask.io' },
       { name: 'Coinbase', url: 'https://wallet.coinbase.com/' }
     ],
     agreement: {
       version: '1.0.0',
       termsUrl: 'https://www.blocknative.com/terms-conditions',
       privacyUrl: 'https://www.blocknative.com/privacy-policy'
     },
     gettingStartedGuide: 'https://blocknative.com',
     explore: 'https://blocknative.com'
   }
 })
 
 // Subscribe to wallet updates
 const wallets$ = onboard.state.select('wallets')
 const { unsubscribe } = wallets$.subscribe(update =>
   console.log('wallets update: ', update)
 )
 
 // unsubscribe when updates are no longer needed
 onDestroy(unsubscribe)
</script>
 
<style>
 button {
   width: 14rem;
   margin: 8px;
 }
</style>
 
<main>
 <div class="cta">
   
						

Observe Ethereum

Blocknative's proven & powerful enterprise-grade infrastructure makes it easy for builders and traders to work with mempool data.

Visit ethernow.xyz

Want to keep reading?

Good choice! We have more articles.

eip-4844,-blobs,-and-blob-gas:-what-you-need-to-know
Ethereum

EIP-4844, Blobs, and Blob Gas: What you need to know

With the upcoming Dencun upgrade, Ethereum will adopt EIP-4844, commonly called proto-danksharding...

introducing-ethernow:-real-time-observability-for-ethereum
Ethereum

Introducing Ethernow: Real-Time Observability for Ethereum

On-chain data tells you what has happened. Pre-chain data tells you why it is happening. For anyone..

mempool-archive-quickstart:-how-to-use-blocknative's-historical-ethereum-mempool-data-to-analyze-private-transactions,-mev,-and-ofas
Blog Nav Post

Mempool Archive Quickstart: How to use Blocknative's historical Ethereum mempool data to analyze private transactions, MEV, and OFAs

Blocknative offers the most exhaustive historical archive of Ethereum's mempool transaction events,..

Connect with us. Build with us.

We love to connect with teams who are building with Blocknative. Tell us about your team and what you would like to learn.

"After first building our own infrastructure, we appreciate that mempool management is a difficult, expensive problem to solve at scale. That's why we partner with Blocknative to power the transaction notifications in our next-generation wallet."

Schedule a demo