wallet-bridge
is a Web3 wallet connection library that supports multiple chains and multiple login methods. It mainly provides functionalities like connecting wallets, sending transactions, signing messages, etc.
- Supported Chains: Ethereum, BNB Smart Chain, Polygon, TRON, Dogecoin.
- Login Methods: WalletConnect, Passkey, Torus.
- Industry Standards: We rely on viem, @wagmi/core, and @wagmi/connectors, which are among the most commonly used libraries in Web3.
dev
: Bootstrap the Storybook preview with Hot Reload.build
: Builds the static storybook project.build:lib
: Builds the component library into the dist folder.lint:fix
: Applies linting based on the rules defined in .eslintrc.js.format:prettier
: Formats files using the prettier rules defined in .prettierrc.test
: Runs testing using watch mode.test:cov
: Runs testing displaying a coverage report.
Install wallet-bridge and its peer dependencies.
yarn add wallet-bridge@^1 @wagmi/core@^2 @wagmi/connectors@^4 viem@^2
import { Wallet } from 'wallet-bridge'
Note:
wallet-bridge
does not support SSR. If your project uses SSR, make sure to check if you are in a browser environment before usingwallet-bridge
. Although this library is developed based on react.js, it can also be used in any frontend project.
To import the Wallet
on demand, you can use the import()
method:
const { Wallet } = await import('wallet-bridge')
To create a new Wallet
object, you can use its constructor and provide the following parameters:
isTestNet
(optional): Whether to use the test network. Defaults tofalse
.loggedInSelectAddress
(optional): Whether to allow users to choose when logging in with Passkey if there are multiple addresses. Defaults totrue
.customChains
(optional): Custom chains sourced from theCustomChain
enum. Defaults to an empty array.customWallets
(optional): Custom wallets sourced from theCustomWallet
enum. Defaults to an empty array.wagmiConfig
(required): Used to configure related information for @wagmi/core, with the typeWagmiConfig
. The default isundefined
. Now, every DApp that relies on WalletConnect needs to obtain a projectId for free from WalletConnect Cloud.gtag
(optional): Used to report some wallet-bridge events to Google Analytics for the purpose of tracking and analyzing user behavior. If you useevent
, you do not need to provide this parameter.event
(optional): If you use nextjs-google-analytics to report data, you can useevent
in place ofgtag
to report wallet-bridge events to Google Analytics for tracking and analyzing user behavior. If you usegtag
, you do not need to provide this parameter.locale
(optional): Used to set the locale. Currently en, zh-CN, zh—TW, zh-HK and zh-MO are supported. If not set, the locale is detected in the order of query parameter lang -> the session storage lang -> browser language -> en.
Example:
import { Wallet } from 'wallet-bridge'
import { createConfig, http } from '@wagmi/core'
import { bsc, bscTestnet, holesky, mainnet as ethereum, polygon, polygonAmoy } from '@wagmi/core/chains'
import { injected, walletConnect } from '@wagmi/connectors'
const walletConnectOptions = {
projectId: 'YOUR_PROJECT_ID', // Get projectId at https://cloud.walletconnect.com
metadata: {
name: '.bit',
description: 'Barrier-free DID for Every Community and Everyone',
url: 'https://d.id',
icons: ['https://d.id/favicon.png'],
},
}
const wagmiConfig = createConfig({
chains: [ethereum, holesky, bsc, bscTestnet, polygon, polygonAmoy],
transports: {
[ethereum.id]: http(),
[holesky.id]: http(),
[bsc.id]: http(),
[bscTestnet.id]: http(),
[polygon.id]: http(),
[polygonAmoy.id]: http(),
},
connectors: [injected(), walletConnect(walletConnectOptions)],
})
const wallet = new Wallet({
isTestNet: false,
loggedInSelectAddress: true,
customChains: [CustomChain.eth],
customWallets: [CustomWallet.metaMask],
wagmiConfig: wagmiConfig,
locale: 'zh-CN',
})
Here are some primary instance methods:
Initialize the wallet login status. It can be initialized globally or before every wallet use, and you can decide whether to continue executing the related business code based on the return value. The initWallet
method checks whether the wallet is already logged in. If logged in, it won't prompt the user to log in again. If not logged in, the involution
parameter can control whether to prompt the user to re-login.
Parameters:
involution
(optional): Typeboolean
. Defaults totrue
. Whether to prompt the user to re-login if not already logged in.
Return Value:
Promise<boolean>
: Indicates whether the wallet has successfully logged in. Returnstrue
if successful; otherwise, returnsfalse
.
Example:
wallet.initWallet().then((success) => {
console.log('Wallet Initialization:', success ? 'Successful' : 'Failed')
})
Display the wallet connection popup.
Parameters:
onlyEth
(optional): Typeboolean
. Whether to display only the Ethereum chain. Defaults tofalse
.
Example:
wallet.connectWallet({ onlyEth: true })
Displays a wallet connection popup. Allows signing while logging in.
Example:
const res = await wallet.connectWalletAndSignData({
signData: {
data: 'hello world',
},
})
console.log(res)
// or EVM EIP-712
const jsonStr =
'{"types":{"EIP712Domain":[{"name":"chainId","type":"uint256"},{"name":"name","type":"string"},{"name":"verifyingContract","type":"address"},{"name":"version","type":"string"}],"Action":[{"name":"action","type":"string"},{"name":"params","type":"string"}],"Cell":[{"name":"capacity","type":"string"},{"name":"lock","type":"string"},{"name":"type","type":"string"},{"name":"data","type":"string"},{"name":"extraData","type":"string"}],"Transaction":[{"name":"DAS_MESSAGE","type":"string"},{"name":"inputsCapacity","type":"string"},{"name":"outputsCapacity","type":"string"},{"name":"fee","type":"string"},{"name":"action","type":"Action"},{"name":"inputs","type":"Cell[]"},{"name":"outputs","type":"Cell[]"},{"name":"digest","type":"bytes32"}]},"primaryType":"Transaction","domain":{"chainId":5,"name":"da.systems","verifyingContract":"0x0000000000000000000000000000000020210722","version":"1"},"message":{"DAS_MESSAGE":"TRANSFER FROM 0x54366bcd1e73baf55449377bd23123274803236e(906.74221046 CKB) TO ckt1qyqvsej8jggu4hmr45g4h8d9pfkpd0fayfksz44t9q(764.13228446 CKB), 0x54366bcd1e73baf55449377bd23123274803236e(142.609826 CKB)","inputsCapacity":"906.74221046 CKB","outputsCapacity":"906.74211046 CKB","fee":"0.0001 CKB","digest":"0x29cd28dbeb470adb17548563ceb4988953fec7b499e716c16381e5ae4b04021f","action":{"action":"transfer","params":"0x00"},"inputs":[],"outputs":[]}}'
const res = await wallet.connectWalletAndSignData({
signData: {
data: JSON.parse(jsonStr),
isEIP712: true,
},
})
console.log(res)
Display the logged-in popup. If the user is already logged in, the popup will show the login information.
Example:
wallet.loggedInfo()
Used for sending transactions.
Parameters:
data
: Transaction parameters.to
: The transaction's recipient address, typestring
.value
: Transaction amount, must be in the smallest unit of the token, typestring
.data
(optional): Transaction memo, typestring
.
Return Value:
Promise<string | undefined>
: After successfully sending the transaction, a transaction hash is returned. If there's any error or issue, it might returnundefined
or throw an error.
Example:
const transactionData = {
to: '0x020881E3F5B7832E752d16FE2710eE855A6977Dc',
value: '10000000000',
data: 'a message',
}
wallet.sendTransaction(transactionData).then((txHash) => {
console.log('Transaction Hash:', txHash)
})
Initialize the signing context and return the signing method. To prevent the browser from blocking the signing popup, ensure that you call initSignContext
before any asynchronous operations in the click event.
Return Value:
Promise<InitSignContextRes>
: Returns an object containing the following methods:signTxList
: Function, specific to .bit business, used for signing transaction lists.signData
: Function, the return value is the signed data.onFailed
: A function, which returns aPromise<IData<any>>
. In case of any errors, callonFailed
to notify and display the error in a popup.onClose
: A function, which returns aPromise<void>
. In some cases, if you want to handle the error yourself and not display it in a popup, useonClose
to close the popup.
Example:
const { signTxList, signData, onFailed, onClose } = await wallet.initSignContext()
const res = await signTxList({})
const res = await signData('0x123')
const res = await signData({}, { isEIP712: true })
await onFailed()
await onClose()
useWalletState
is a React hook for retrieving and listening to the wallet's state.
Returns:
-
walletSnap
: A current snapshot of thewalletState
with typeWalletState
, which contains the following fields:protocol
: The protocol type of the wallet, of typeWalletProtocol
.address
: The currently logged-in wallet address, of typestring
.coinType
: The type of token, of typeCoinType
.walletName
: The wallet name, of typestring
.hardwareWalletTipsShow
: Whether the hardware wallet tips are shown or not, of typeboolean
.deviceData
: Device data during Passkey login, of typeIDeviceData
.ckbAddresses
: List of CKB addresses that the device can manage during Passkey login, of typestring[]
.deviceList
: List of backup devices, of typestring[]
.isTestNet
: Whether it's on testnet or not, of typeboolean
.loggedInSelectAddress
: Whether to select an address when logging in with Passkey with multiple addresses available, default istrue
.canAddDevice
: Whether a backup device can be added or not, of typeboolean
.iCloudPasskeySupport
: Whether the current environment supports storing the passkey in iCloud, of typeboolean
.customChains
: Custom chains to be displayed, of typeCustomChain[]
.customWallets
: Custom wallets to be displayed, of typestring[]
.alias
: The .bit alias set for the currently logged-in wallet address, of typestring
.locale
: The language currently in use, of typestring
.chainId
: When logging in with an EVM chain wallet, it represents the corresponding chain ID, of typenumber
. When logging in with an TRON wallet, it represents the corresponding chain ID, of typestring
.
Example:
function Component() {
const { walletSnap } = wallet.useWalletState()
return <div>Address: {walletSnap.address}</div>
}
Used to immediately get the current snapshot of the wallet's state.
Returns:
Same as the return of useWalletState
.
Example:
const { walletSnap } = wallet.getWalletState()
console.log(walletSnap.address)
Verify if the passkey signature is correct.
Parameters:
params
: Transaction parameters.message
: Original message, of typestring
.signature
: Result of message signature, of typestring
.
Return value:
Promise<boolean>
: If the signature is correct, it returnstrue
. Any errors or issues may result in an exception being thrown.
Example:
wallet._verifyPasskeySignature({ message: '0x123', signature: '0x40b4a569e0cb53163f...' }).then((result) => {
console.log('result: ', result)
})
Used to set the locale. Currently en, zh-CN, zh—TW, zh-HK and zh-MO are supported. If not set, the locale is detected in the order of query parameter lang -> the session storage lang -> browser language -> en.
Example:
wallet.setLocale('en')
wallet.setLocale('zh-CN')
wallet.setLocale('zh—TW')
wallet.setLocale('zh-HK')
wallet.setLocale('zh-MO')