Skip to Content
dApps

Provider API

OneKey Browser Extension injects a global API into websites visited by its users at window.$onekey.ethereum. This API allows websites to request users’ Ethereum accounts, read data from blockchains the user is connected to, and suggest that the user sign messages and transactions. A detected provider does not mean the user has connected an account or authorized a request.

The Ethereum JavaScript provider API is specified by EIP-1193 . For modern applications, it is highly recommended to use the EIP-6963  standard for discovering multiple wallet providers, which avoids conflicts between different browser extensions.

Provider Detection

To ensure compatibility and a smooth user experience in a multi-wallet environment, it is highly recommended to detect providers using the EIP-6963 standard.

OneKey fully supports EIP-6963, which allows dApps to discover multiple installed wallet providers without conflicts. This is the modern, recommended approach for all dApps.

// This code snippet demonstrates how to listen for announced providers // and store them for your dApp to use. let onekeyProvider = null; const onAnnounceProvider = (event) => { // The event.detail contains the provider info and the provider object itself. // event.detail = { info: { uuid, name, icon, rdns }, provider } if (event.detail.info.rdns === 'so.onekey.app.wallet') { onekeyProvider = event.detail.provider; } // You can also store all providers in an array to let users choose. }; // Listen for the announcement event from all wallets window.addEventListener('eip6963:announceProvider', onAnnounceProvider); // It's also good practice to dispatch a request event to prompt wallets // that may have loaded after the initial page load. window.dispatchEvent(new Event('eip6963:requestProvider')); // Use the discovered provider when the user selects OneKey and clicks Connect. // Announcements are asynchronous; do not treat a fixed timeout as proof that // the wallet is not installed. Remove the event listener when your UI unmounts.

Legacy Detection & Provider Objects

For compatibility with older dApps, OneKey also injects its provider into window.ethereum.

  • window.ethereum: This is the commonly used provider object. However, if a user has multiple wallets installed, this variable can be overwritten, leading to conflicts. OneKey injects here to maximize compatibility.
  • window.$onekey.ethereum: To avoid conflicts, OneKey also provides its provider via this private, namespaced variable. This ensures a dApp can specifically target OneKey if needed, though using EIP-6963 is preferred.

Basic Usage

For any non-trivial Ethereum web application (dApp) to work, you will need to accomplish three fundamental tasks:

  1. Detect an Ethereum Provider: You must first find out if the user has a wallet like OneKey installed. The recommended way to do this is by using the EIP-6963 standard, as detailed in the Provider Detection section above.
  2. Access User Accounts: Once a provider is detected, you need to request permission to view the user’s accounts. This is almost always done by calling the eth_requestAccounts method on the provider object.
  3. Monitor Network Changes: The user can switch between different networks (like Ethereum Mainnet and Sepolia) at any time. Your dApp must listen for the chainChanged event to stay aware of the currently connected network.

The provider object is the essential tool for building a full-featured Web3 application. While you can use the provider API directly for all interactions, many developers prefer using a convenience library to simplify development. We recommend robust, community-vetted libraries like ethers.js or viem, which provide higher-level abstractions and utilities.

Chain IDs

Query the selected chain instead of hard-coding a wallet support list. Chain IDs returned by the provider are hexadecimal strings.

const chainId = await provider.request({ method: 'eth_chainId' }); console.log(chainId); // For example, '0x1' for Ethereum mainnet.

Validate the chain against your application’s supported networks before constructing a transaction. See RPC API for adding a network.

Methods

Once you have obtained a provider object (e.g., via EIP-6963), you can use the following EIP-1193 methods to interact with the user’s wallet.

eth_requestAccounts

Use eth_requestAccounts to request one or more accounts from the user’s wallet. Calling this will typically prompt the user with a connection request.

try { const accounts = await window.$onekey.ethereum.request({ method: 'eth_requestAccounts' }); // handle accounts } catch (error) { // handle error, e.g., user rejected request }

window.$onekey.ethereum.isConnected()

Tip
Note that this method has nothing to do with the user’s accounts.
You may often encounter the word “connected” in reference to whether a web3 site can access the user’s accounts. In the provider interface, however, “connected” and “disconnected” refer to whether the provider can make RPC requests to the current chain.

interface EthereumProvider { isConnected(): boolean; }

Returns true if the provider is connected to the current chain, and false otherwise.

If the provider is not connected, the page will have to be reloaded in order for connection to be re-established. Please see the connect and disconnect events for more information.

window.$onekey.ethereum.request(args)

interface RequestArguments { method: string; params?: unknown[] | object; } interface EthereumProvider { request(args: RequestArguments): Promise<unknown>; }

Use request to submit RPC requests to Ethereum via OneKey Browser Extension. It returns a Promise that resolves to the result of the RPC method call.

The params and return value will vary by RPC method. In practice, if a method has any params, they are almost always of type Array<any>.

If the request fails for any reason, the Promise will reject with an Ethereum RPC Error.

OneKey Browser Extension supports most standardized Ethereum RPC methods, in addition to a number of methods that may not be supported by other wallets.

See RPC API for method details.

Example

const provider = window.$onekey?.ethereum; if (!provider) throw new Error('OneKey Ethereum provider is unavailable.'); const [from] = await provider.request({ method: 'eth_requestAccounts' }); const to = '<RECIPIENT_EVM_ADDRESS>'; // Replace with a valid 20-byte address. try { const transactionHash = await provider.request({ method: 'eth_sendTransaction', params: [{ from, to, value: '0x0' }], }); console.log('Submitted transaction:', transactionHash); } catch (error) { console.error(error.code, error.message); }

Events

The OneKey Browser Extension provider implements the Node.js EventEmitter API. This section details the events emitted via that API.

There are innumerable EventEmitter guides elsewhere, but you can listen for events like this:

window.$onekey.ethereum.on('accountsChanged', (accounts) => { // Handle the new accounts, or lack thereof. // "accounts" will always be an array, but it can be empty. }); window.$onekey.ethereum.on('chainChanged', (chainId) => { // Handle the new chain. // Correctly handling chain changes can be complicated. // We recommend reloading the page unless you have good reason not to. window.location.reload(); });

connect

interface ConnectInfo { chainId: string; } const handler = (connectInfo: ConnectInfo) => { console.log(connectInfo); }; window.$onekey.ethereum.on('connect', handler);

The OneKey Browser Extension provider emits this event when it first becomes able to submit RPC requests to a chain.

We recommend using a connect event handler and the window.$onekey.ethereum.isConnected() method in order to determine when/if the provider is connected.

disconnect

const handler = (error: ProviderRpcError) => { console.log(error); }; window.$onekey.ethereum.on('disconnect', handler);

The OneKey provider emits this event if it becomes unable to submit RPC requests to any chain. In general, this will only happen due to network connectivity issues or some unforeseen error.

Once disconnect has been emitted, the provider will not accept any new requests until the connection to the chain has been re-established, which requires reloading the page. You can also use the window.$onekey.ethereum.isConnected() method to determine if the provider is disconnected.

accountsChanged

const handler = (accounts: Array<string>) => { console.log(accounts); }; window.$onekey.ethereum.on('accountsChanged', handler);

The OneKey provider emits this event whenever the return value of the eth_accounts RPC method changes. eth_accounts returns an array of exposed account addresses, which can be empty. Each returned address is an account the caller is permitted to access. Callers are identified by their URL origin, which means that all sites with the same origin share the same permissions.

This means that accountsChanged will be emitted whenever the user’s exposed account address changes.

chainChanged

Tip
Query eth_chainId to read the selected chain.

const handler = (chainId: string) => { console.log(chainId); }; window.$onekey.ethereum.on('chainChanged', handler);

The OneKey Browser Extension provider emits this event when the currently connected chain changes.

All RPC requests are submitted to the currently connected chain. Therefore, it’s critical to keep track of the current chain ID by listening for this event.

A common way to handle this is to reload the page:

window.$onekey.ethereum.on('chainChanged', (_chainId) => window.location.reload());

message

interface ProviderMessage { type: string; data: unknown; } const handler = (message: ProviderMessage) => { console.log(message); }; window.$onekey.ethereum.on('message', handler);

The OneKey provider emits this event when it receives some message that the consumer should be notified of. The kind of message is identified by the type string.

EIP-1193 defines message for provider notifications. Do not assume that an injected provider supports eth_subscribe; verify the requested method in your target wallet and network.

Errors

All errors thrown or returned by the OneKey provider follow this interface:

interface ProviderRpcError extends Error { message: string; code: number; data?: unknown; }

The request(args) promise rejects when a request fails. You can often use the code property to determine why the request failed.

Common codes and their meaning include:

  • 4001: The request was rejected by the user.
  • -32602: The parameters were invalid.
  • -32603: Internal error.

For the complete list of errors, please see EIP-1193  and EIP-1474 .

Last updated on