Onboard.js

Blocknative’s open-source JavaScript library to onboard users to Ethereum apps. Help your users transact with ease by enabling wallet selection, connection, wallet checks, and real-time state updates.
Example desktop wallet select modal
Example mobile wallet select modal

Quickstart

It should take less than 5 minutes to get going with Blocknative Onboard.

Create a Blocknative Account

Go to the Account Dashboard at https://account.blocknative.com/ and setup an account with an email address. You will receive an email to confirm your account.

Create your API Key

On the Account Dashboard, create an API key with your choice of name using the API Keys link (https://account.blocknative.com/api-keys). API keys segment analytics data. Consider using different API keys for development, staging, and production releases.

API key creation in Account Dashboard

Install the widget using npm

npm install bnc-onboard

Initialize the Library

Use the minimum required config. There are more options available as detailed in the initialization section.

import Onboard from 'bnc-onboard'
import Web3 from 'web3'
let web3;
const onboard = Onboard({
dappId: apiKey, // [String] The API key created by step one above
networkId: networkId // [Integer] The Ethereum network ID your Dapp uses.
subscriptions: {
wallet: wallet => {
web3 = new Web3(wallet.provider)
}
}
});

The wallet subscription function will be called when the user selects a wallet so you can instantiate web3 with the selected provider.

Onboard User

Ask the user to select a wallet and then check wallet is ready to transact.

await onboard.walletSelect();
await onboard.walletCheck();

And you are live!

Sample onboard modal

Screencasts

See the above Quickstart guide in a screencast:

Onboard.js Quickstart Screencast

For a deeper dive with additional wallets that builds on the Quick Start, see this screencast:

Additional Wallets Screencast

Initialization

Options

const options = {
dappId: String,
networkId: Number,
darkMode: Boolean
subscriptions: {
address: Function,
network: Function,
balance: Function,
wallet: Function
},
walletSelect: {
heading: String,
description: String,
wallets: Array
},
walletCheck: Array
}
}

dappId - [required]

Your unique apiKey that identifies your application. You can generate a dappId by visiting the Blocknative account page and create a free account.

networkId - [required]

The Ethereum network id that your application runs on. The following values are valid:

  • 1 Main Network

  • 3 Ropsten Test Network

  • 4 Rinkeby Test Network

  • 5 Goerli Test Network

  • 42 Kovan Test Network

darkMode - [optional] - Default: false

Opt for the Dark color scheme or not.

subscriptions - [optional]

An object of callback functions that get called whenever the corresponding value changes. Use these callbacks to sync your UI or to store the values for use elsewhere in your code. Valid parameters to register callbacks for are:

  • address - called with the user's current address [string]

  • network - called with the user's current network id [number]

  • balance - called with the user's current balance [string]

  • wallet - called with the user's current wallet [object: { provider, name, instance }]

walletSelect - [optional]

A object that defines how the wallet select screen will render using the following parameters:

  • heading - [optional] : A string that will be the wallet select modal heading

  • description - [optional] : A string that will be the wallet select modal description

  • wallets - [optional] : An array of wallet modules or wallet initialization objects that the user can select from

If not provided, then the default heading and description and wallets that don't require initialization will be included for you.

walletCheck - [optional]

An array of wallet check modules or wallet check initialization objects that will be used to check if the user is ready to transact.

Initialize Onboard

To initialize Onboard, simply import the library and call it with your initializationOptions:

import Onboard from 'bnc-onboard'
const initializationOptions = {
// ..... options here
}
const onboard = Onboard(initializationOptions)

The return value will be the initialized onboard library which contains the API functions below.

API

walletSelect

When you are ready to get a user to select a wallet and connect it to your Dapp, you can call the walletSelect function to display the wallet select modal:

const walletSelected = await onboard.walletSelect()
// returns a Promise that:
// resolves with true if the user selected a wallet
// resolves with false if the user exited from the wallet select modal

This function will show a modal that displays buttons for all of the wallets that you initialized onboard with. It will guide the user through the process of connecting to the wallet that they select. Once the process is successful the function will resolve with true. This means that the provider subscription will have been called with the provider of the selected wallet and you can go ahead and instantiate your web3 library with the provider and also instantiate your contracts.

walletCheck

Once a wallet is selected, you will want to make sure that the user's wallet is prepared and ready to transact by calling the walletCheck function:

const readyToTransact = await onboard.walletCheck()
// returns a Promise that:
// resolves with true if user is ready to transact
// resolves with false if user exited before completing all wallet checks

This function will run through the walletCheck modules that were passed in via initialization sequentially, making sure the user has passed the condition contained in each module and eventually resolves with true if the user completed the sequence. This means that the user is ready to transact. This function is useful to call before every transaction to make sure that nothing has changed since the last time it was called.

config

You can update some configuration parameters by passing a config object in to the config function:

onboard.config({ darkMode: true, networkId: 4 })

Available parameters that you can update are:

  • darkMode - [boolean]

  • networkId - [number]

Built-in Modules

Wallet Modules

The following list of wallet modules are included in Onboard and their initializationObject is listed each wallet:

Wallets

  • metamask

const initializationObject = {
walletName: 'metamask'
}
  • dapper

const initializationObject = {
walletName: 'dapper'
}
  • walletConnect

const initializationObject = {
walletName: 'walletConnect',
// your infura id [String]
infuraKey: 'INFURA_KEY'
}
  • portis

const initializationObject = {
walletName: 'portis',
// your Portis apiKey [String]
apiKey: 'PORTIS_KEY'
}
  • fortmatic

const initializationObject = {
walletName: 'fortmatic',
// your Fortmatic apiKey [String]
apiKey: 'FORTMATIC_KEY'
}
  • squarelink

const initializationObject = {
walletName: 'squarelink',
// your Squarelink apiKey [String]
apiKey: 'SQUARELINK_KEY'
}
  • authereum

const initializationObject = {
walletName: 'authereum'
}
  • trust

const initializationObject = {
walletName: 'trust'
}
  • coinbase

const initializationObject = {
walletName: 'coinbase'
}

Initialization:

To initialize the built in wallet modules, an array of wallet initialization objects needs to be passed to the walletSelect.wallets parameter of the Onboard initialization object. The order of the array is the order that the wallets will be displayed. Mobile wallets will be displayed when a user is on a mobile device and desktop wallets are displayed when they are on a desktop device.

Each wallet initialization object can have a preferred parameter which will define whether it is shown at the top of the selection screen. If any of the wallets are set to preferred, then all other wallets that aren't, will be hidden until the user clicks the "Show More" button. If there are no wallets set to preferred, then the first four wallets will be shown and the remaining wallets will be hidden until the show more button is clicked.

import Onboard from 'bnc-onboard'
const wallets = [
{ walletName: "coinbase", preferred: true },
{ walletName: "trust", preferred: true },
{ walletName: "metamask", preferred: true },
{ walletName: "dapper", preferred: true },
{
walletName: "fortmatic",
apiKey: FORTMATIC_KEY,
preferred: true
},
{
walletName: "portis",
apiKey: PORTIS_KEY,
preferred: true
},
{
walletName: "squarelink",
apiKey: SQUARELINK_KEY
},
{ walletName: "authereum" },
{
walletName: "walletConnect",
infuraKey: INFURA_KEY
}
]
const onboard = Onboard({
//... other options
walletSelect: {
wallets: wallets
}
})

Wallet Check Modules

The following wallet check modules are included in Onboard:

  • connect: Checks that the Dapp has access to the users' accounts and fires the connect function if the selected wallet has one to prompt the user to allow access.

const initializationObject = {
checkName: 'connect'
}
  • network: Checks that the users' wallet is connected to the network that the modules were initialized with.

const initializationObject = {
checkName: 'network'
}
  • balance: Checks that the users' account has the minimum balance as defined when initialized.

const initializationObject = {
checkName: 'balance',
// The minimum balance in wei required [String]
minimumBalance: '1000000'
}

Initialization:

import Onboard from 'bnc-onboard'
const walletChecks = [
{ checkName: 'connect' },
{ checkName: 'network' },
{ checkName: 'balance', minimumBalance: '1000000' }
]
const onboard = Onboard({
//... other options
walletCheck: walletChecks
})

Creating Custom Modules

Onboard has been built so that custom wallet and wallet check modules can be plugged in to allow for the breadth of different wallets and on-boarding flows that are needed across the web3 ecosystem.

Custom Wallet Modules

A wallet module is an abstraction that allows interoperability between wallets within Onboard.

A wallet module has the following properties:

name - [string][required]

The name of the wallet.

wallet - [function][required]

A function that is called when this wallet is selected. It is called with a helpers object that includes some helper functions that make it easier to create the return object. The helpers object contains the following methods:

  • getProviderName - A function that takes a provider as an argument and will return the name of the most common providers.

  • createLegacyProviderInterface - A function that takes the provider as an argument and returns a walletInterface. Legacy refers to a provider that has not implemented EIP-1102.

  • createModernProviderInterface - A function that takes the provider as an argument and returns a walletInterface. Modern refers to a provider that has implemented EIP-1102. This will work for most providers and is a quick way to create an interface.

  • BigNumber - A bignumber.js function for number calculations.

  • getNetwork - A function that takes a provider and will make a JSON-RPC call to get the network.

  • getAddress - A function that takes a provider and will make a JSON-RPC call to get the address.

  • getBalance - A function that takes a provider and will make a JSON-RPC call to get the balance.

The wallet function must return a Promise that resolves to an object that has the following properties:

provider - the JavaScript provider for this wallet. [required]

instance - for SDK wallets instances that are separate from the provider. [optional]

interface - a walletInterface or null if the user's current provider is not this wallet (for extension and mobile wallets). [required]

walletInterface

An abstraction built on top of an Ethereum JavaScript provider allowing interoperability with wallets and providers of any architecture. A valid walletInterface implements the following methods and attributes:

name - The name of the wallet. [string][required]

connect - A function that requests account access and returns a Promise that resolves or rejects once the user confirms or rejects the request. [function][optional]

disconnect - A function to clean up / destroy any instances (mostly for SDK wallets). Will be called when a new wallet has been selected. [function][optional]

loading - A function that returns a Promise that resolves when the wallet has finished loading. This is to show a loading spinner as the wallet popup is loading (mostly for SDK wallets). [function][optional]

address - A stateSyncer object (see below for details). The get function on this stateSyncer must return a string which is the wallet address.

network - A stateSyncer object (see below for details). The get function on this stateSyncer must return a number which is the wallet network id.

balance - A stateSyncer object (see below for details). The get function on this stateSyncer must return a string which is the wallet address balance.

stateSyncer

An object that has either a get function or a onChange function and is used to keep user state in sync. The onChange method is preferred as it doesn't require background polling to keep in sync.

The get function returns a promise that resolves with a value.

The onChange function takes a setState function as an argument and is used to set the state. Often it is needed to use the setState function to set the initial state and then register it to be called every time it changes.

iconSrc - [string][optional]

A source for the wallet logo icon.

iconSrcSet - [string][optional]

A source for the hi-res wallet logo icon.

svg - [string][optional]

A svg element string for the wallet logo icon.

A link to install this wallet (extension and injected provider wallets).

installMessage - [function][optional]

A function that will be called when a user has selected this wallet, but the wallet function did not return a wallet interface. This is generally only needed if this wallet injects the provider via an extension or mobile wallet and the user doesn't have the extension installed or is on the wrong mobile browser. The function will be called with an object that has two properties: currentWallet (the name of the wallet that has been detected by Onboard) and selectedWallet (the name of the selected wallet), and must return a string (that can include html) that instructs the user to install this wallet.

desktop - [boolean][optional]

Whether the wallet is a desktop wallet or not.

mobile - [boolean][optional]

Whether the wallet is a mobile wallet or not.

preferred - [boolean][optional

Whether this wallet will be displayed as a preferred wallet.

Example

import Onboard from 'bnc-onboard'
import SomeSDKWallet from 'some-sdk-wallet'
const customExtensionWalletLogo = `
<svg
height="40"
viewBox="0 0 40 40"
width="40"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m2744.99995 1155h9.99997"
fill="#617bff"
/>
</svg>
`
const customSDKWalletLogo = `
<svg
height="40"
viewBox="0 0 40 40"
width="40"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m2744.99995 1155h9.99997"
fill="#617bff"
/>
</svg>
`
// create custom wallet
const customExtensionWallet = {
name: 'Extension Wallet',
svg: customExtensionWalletLogo,
wallet: async helpers => {
const { createModernProviderInterface } = helpers
const provider = window.ethereum
const correctWallet = window.ethereum.currentProvider.isExtensionWallet
return {
provider,
interface: correctWallet ? createModernProviderInterface(provider) : null
}
},
link: 'https://some-extension-wallet.io',
installMessage: wallets => {
const { currentWallet, selectedWallet } = wallets
if (currentWallet) {
return `You have ${currentWallet} installed already but if you would prefer to use ${selectedWallet} instead, then click below to install.`
}
return `You will need to install ${selectedWallet} to continue. Click below to install.`
},
desktop: true
}
// create custom wallet
const customSDKWallet = {
name: 'SDK Wallet',
svg: customSDKWalletLogo,
wallet: async helpers => {
const { createModernProviderInterface } = helpers
const instance = new SomeSDKWallet({ apiKey: 'sd3d3fwd' })
const provider = instance.getProvider()
return {
provider,
interface: createModernProviderInterface(provider),
instance
}
},
desktop: true,
mobile: true
}
const defaultWallets = [
{ walletName: 'metamask' },
{ walletName: 'coinbase' }
]
// initialize onboard
const onboard = Onboard({
//... other options
walletSelect: {
wallets: [...defaultWallets, customExtensionWallet, customSDKWallet]
},
//... other options
}
})

Custom Wallet Check Modules

You can create custom onboarding flows by stringing together a sequence of wallet check modules that check that the users' state is correct before moving forward. A wallet check module is a function that gets called with an object which contains the users' current state and either returns a result of undefined if that check has passed or a modalObject if it failed. A wallet check module can also return a Promise that resolves to the check result, allowing asynchronous actions and checks to be a part of your onboarding flow.

A wallet check module will be called with a state object with the following parameters and functions:

address - The users' current address. [string]

network - The users' current network id. [number]

balance - The users' current account balance in wei. [string]

appNetworkId - The networkId that the Dapp is configured to work with. [number]

wallet - The users' wallet object containing the properties: provider, interface, connect, name, loading and instance. [object]

mobileDevice - Whether the user is on a mobile device or not. [boolean]

BigNumber - A bignumber.js function for number calculations. [function]

walletSelect - Call this to switch wallets, will close wallet check dialog and open wallet select dialog. [function]

exit - Call to exit wallet check dialog. [function]

The module function then needs to evaluate a condition and then return a result of undefined if the condition has been met or a modalObject if not. The modalObject is an object with the following properties:

heading - The heading for the wallet check modal. [string][required

description - The description for the wallet check modal. [string][required]

eventCode - An event code that is used for your back-end analytics dashboard. [string][required]

button - A object with an onclick property to register a function to run when the button is clicked, and a text property for the button text [object][optional]

icon - A icon to be displayed next to the heading. [string][optional]

action - A function to run upon showing the modal that returns a Promise that resolves when finished or rejects with an error. [function][optional]

loading - A Promise that resolves when a process has finished loading so that a spinner displays on the modal when loading. [Promise][optional]

Example

For a user to interact with your Dapp, they may require a token balance (ie Dai). You could build a module that checks that a user has the required token balance to continue:

import Onboard from 'bnc-onboard'
import ethers from 'ethers'
import erc20 from './erc20'
function tokenBalance({ tokenAddress, minimumBalance, tokenName }) {
let ethersProvider;
let tokenContract;
return async stateAndHelpers => {
const {
wallet: { provider },
address,
BigNumber
} = stateAndHelpers;
if (!tokenContract) {
ethersProvider = new ethers.providers.Web3Provider(provider);
tokenContract = new ethers.Contract(tokenAddress, erc20, ethersProvider);
}
const tokenDecimals = await tokenContract.decimals();
const divideBy = new BigNumber(10).pow(tokenDecimals);
const tokenBalanceResult = await tokenContract
.balanceOf(address)
.then(res => res.toString());
const tokenBalance = new BigNumber(tokenBalanceResult).div(divideBy);
if (tokenBalance.lt(minimumBalance)) {
return {
heading: `Get Some ${tokenName}`,
description: `You need to have at least ${minimumBalance} ${tokenName} to interact with this Dapp. Send some more ${tokenName} to this address or switch to another address that has a higher ${tokenName} balance.`,
eventCode: "tokenBalance",
icon: `
<svg
height="18"
viewBox="0 0 429 695"
width="18" xmlns="http://www.w3.org/2000/svg"
>
<g
fill="currentColor"
fill-rule="evenodd"
>
<path d="m0 394 213 126.228516 214-126.228516-214 301z"/>
<path d="m0 353.962264 213.5-353.962264 213.5 353.962264-213.5 126.037736z"/>
</g>
</svg>
`
};
}
};
}
const defaultWalletChecks = [
{ checkName: 'connect' },
{ checkName: 'network' },
{ checkName: 'balance', minimumBalance: '100000' }
]
const tokenBalanceCheck = tokenBalance({tokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', tokenName: 'Dai', minimumBalance: 5})
const onboard = Onboard({
//... other options
walletCheck: [...defaultWalletChecks, tokenBalanceCheck]
})

Customizing CSS

To gain the required specificity to override the default styles, you need to use the class name .bn-onboard-custom plus the class name that you would like to override in your CSS file. For example, if you would like to customize the font-family for the onboard modals, then you would target the top level element that has the class .bn-onboard-modal in your CSS file:

.bn-onboard-custom .bn-onboard-modal {
font-family: Roboto;
}

Below is a list of the main classes that you can target to customize the CSS:

.bn-onboard-modal - The full page modal container.

.bn-onboard-modal-content - The container for the modal content.

.bn-onboard-modal-header - The header of the modal

.bn-onboard-modal-content-header-heading - The heading within the header.

.bn-onboard-select-description - The wallet select modal description.

.bn-onboard-modal-select-wallets - The unordered list of wallets.

.bn-onboard-icon-button - The wallet button.

.bn-onboard-modal-selected-wallet - Selected wallet modal content.

Get Started Today

Sign up for a free Blocknative Account at https://account.blocknative.com/ with your work email address.

If you have any questions, connect with the team on our discord

Sandbox