React + wagmi
Connect to OneKey from React apps using wagmi and the injected EIP‑1193 provider
This guide shows a minimal, EIP‑1193‑based way to connect OneKey from React apps using wagmi. Core idea: prefer OneKey’s dedicated injection (window.$onekey.ethereum), then fall back to multi‑provider list or generic window.ethereum.
Install
npm i wagmi viemwagmi v2 is built on viem. This guide uses the Injected connector to work with injected wallets (OneKey / other EIP‑1193 providers).
Create a OneKey‑first injected connector
Prefer OneKey’s dedicated injection to avoid ambiguity when multiple wallets are installed.
// onekeyConnector.ts
import { createConfig, http } from 'wagmi'
import { mainnet, polygon, arbitrum, base, optimism } from 'wagmi/chains'
import { injected } from 'wagmi/connectors'
function getOneKeyFirstProvider(): any {
// 1) Prefer OneKey’s dedicated injection
const onekey = (window as any)?.$onekey?.ethereum
if (onekey) return onekey
// 2) Fallback: find OneKey from multi-provider list
const list = (window as any)?.ethereum?.providers
const okFromList = list?.find((p: any) => p?.isOneKey || p?.onekey || (typeof p?.isOneKey === 'function' && p.isOneKey()))
if (okFromList) return okFromList
// 3) Final fallback: single injected provider
return (window as any)?.ethereum
}
export const config = createConfig({
chains: [mainnet, polygon, arbitrum, base, optimism],
connectors: [
injected({
target() {
return {
id: 'onekey',
name: 'OneKey',
provider: getOneKeyFirstProvider,
}
},
shimDisconnect: true,
}),
],
transports: {
[mainnet.id]: http(),
[polygon.id]: http(),
[arbitrum.id]: http(),
[base.id]: http(),
[optimism.id]: http(),
},
})Notes
Prefer
window.$onekey.ethereumto keep behavior deterministic in multi‑wallet environments.If OneKey is not installed, the connector falls back to other injected providers.
Trigger
eth_requestAccountson a user gesture and handle4001(user rejected), as in the legacy docs.
App setup
Connect and read account
Sign and send
Events and network
Listen to
accountsChanged/chainChangedand refresh session state accordingly.Network switching/adding:
wallet_switchEthereumChainandwallet_addEthereumChain.
Mobile and deeplinks
For mobile or WebViews, use deeplinks carrying a WalletConnect URI.
Prefer
onekey-wallet://wc?uri={encodeURIComponent(wcUri)}; fall back to the Universal Link.See: Use deeplinks.
Troubleshooting
4001: user rejected (see legacy docs examples)
Optional: EIP‑6963 (multi‑wallet discovery)
If desired, use EIP‑6963 to discover installed wallets first and prefer OneKey when available. Example:
Last updated
Was this helpful?