OneKey Docs
  • 👋GUIDE
    • Introduction
    • Web App Integration Developer
    • Hardware Integration Developer
    • External Contribution Guide
    • Common Terms
  • 🔮Connect To Software
    • Compatible with Metamask
      • detectEthereumProvider
    • Support Wallet Kit
      • Web3 Onboard
      • Rainbowkit
      • Aptos Wallet Adapter
      • Web3Modal
    • WebApp Connect OneKey
      • ETH
        • Provider API
        • RPC API
        • Accessing Accounts
        • Sending Transactions
        • Signing Data
      • BTC
        • Guide
        • API Reference
          • requestAccounts
          • getAccounts
          • getNetwork
          • switchNetwork
          • getPublicKey
          • getBalance
          • getInscriptions
          • sendBitcoin
          • sendInscription
          • signMessage
          • pushTx
          • signPsbt
          • signPsbts
          • pushPsbt
          • inscribeTransfer (Deprecated)
        • Event
      • Nostr
        • Guide
        • API Reference
          • getPublicKey
          • signEvent
          • signSchnorr
          • getRelays
          • nip04.encrypt
          • nip04.decrypt
        • Event
      • WebLN
        • Guide
        • API Reference
          • enable
          • getInfo
          • makeInvoice
          • sendPayment
          • signMessage
          • verifyMessage
          • lnurl
          • getBalance
        • Event
      • NEAR
        • Introduction
        • Integrating
          • Install the Provider SDK
          • Detecting the Provider
          • Establishing a Connection
          • Accessing Accounts
          • Detecting Provider Network
          • Watch Accounts & Network Status
          • Sending Transactions
            • Create Transaction
            • Sign and Send Transaction
            • Signing Transaction
          • Signing Messages
          • RPC API Calling
          • Debug Logging
          • Migrate from Near Web Wallet
        • Reference
          • API Reference
          • Trouble Shooting
        • Resources
          • Example & Demo
          • FAQ
      • SOLANA
        • Detecting the Provider
        • Establishing a Connection
        • Sending a Transaction
        • Signing a Message
    • Using WalletConnect
      • ETH
      • APTOS
        • Wallet Connect API
  • 📟Connect to Hardware
    • Hardware SDK
      • Started
      • Install SDK
      • Config Event
      • Common Params
      • Path Params
      • Error Code
      • API Reference
        • Basic API
          • Init SDK
          • Search Devices
          • Get Features
          • Get Passphrase State
          • Cancel Request
          • Response UI Event
        • Device API
          • deviceSupportFeatures
          • checkBridgeStatus
          • checkTransportRelease
          • checkFirmwareRelease
          • checkBLEFirmwareRelease
          • deviceChangePin
          • deviceReset
          • deviceSettings
          • deviceUpdateReboot
          • deviceVerify
          • deviceWipe
          • firmwareUpdate
        • Bitcoin & Bitcoin forks
          • btcGetAddress
          • btcGetPublicKey
          • btcSignMessage
          • btcSignTransaction
          • btcVerifyMessage
        • Ethereum & EVM
          • evmGetPublicKey
          • evmGetAddress
          • evmSignTransaction
          • evmSignTypedData
          • evmSignMessage
          • evmVerifyMessage
        • Algorand
          • algoGetAddress
          • algoSignTransaction
        • Aptos
          • aptosGetAddress
          • aptosGetPublicKey
          • aptosSignMessage
          • aptosSignTransaction
        • Alephium
          • alephiumGetAddress
          • alephiumSignMessage
          • alephiumSignTransaction
        • Cardano
          • cardanoGetAddress
          • cardanoGetPublicKey
          • cardanoSignMessage
          • cardanoSignTransaction
        • Conflux
          • confluxGetAddress
          • confluxSignMessage
          • confluxSignMessageCIP23
          • confluxSignTransaction
        • Cosmos
          • cosmosGetAddress
          • cosmosGetPublicKey
          • cosmosSignTransaction
        • Dynex
          • dnxGetAddress
          • dnxSignTransaction
        • FileCoin
          • filecoinGetAddress
          • filecoinSignTransaction
        • Kaspa
          • kaspaGetAddress
          • kaspaSignTransaction
        • Near
          • nearGetAddress
          • nearSignTransaction
        • Nervos
          • nervosGetAddress
          • nervosSignTransaction
        • Nostr
          • nostrGetPublicKey
          • nostrSignEvent
          • nostrSignSchnorr
          • nostrEncryptMessage
          • nostrDecryptMessage
        • NEM
          • nemGetAddress
          • nemSignTransaction
        • Nexa
          • nexaGetAddress
          • nexaSignTransaction
        • Polkadot
          • polkadotGetAddress
          • polkadotSignTransaction
        • Ripple
          • xrpGetAddress
          • xrpSignTransaction
        • Scdo
          • scdoGetAddress
          • scdoSignMessage
          • scdoSignTransaction
        • Solana
          • solGetAddress
          • solSignTransaction
        • Starcoin
          • startcoinGetAddress
          • starcoinGetPublicKey
          • starcoinSignMessage
          • starcoinSignTransaction
          • starcoinVerifyMessage
        • Stellar
          • stellarGetAddress
          • stellarSignTransaction
        • Sui
          • suiGetAddress
          • suiGetPublicKey
          • suiSignMessage
          • suiSignTransaction
        • Tron
          • tronGetAddress
          • tronSignMessage
          • tronSignTransaction
        • Ton
          • tonGetAddress
          • tonSignMessage
          • tonSignProof
      • Advanced
        • Passphrase
        • Common SDK Guide
        • Low-level transport plugin
        • OneKey Message Protocol
      • Tutorial: Get started with OneKey
    • Air Gap SDK
      • Started
      • Tutorial: Wallet Integration
      • API Reference
        • Basic API
          • CryptoHDkey
          • CryptoCoinInfo
          • CryptoKeypath
        • Ethereum & EVM
          • EthSignRequest
          • EthSignature
  • ⛳Best Practice
    • Registering Your Contract's Method Names
    • Registering Tokens with Users
    • Defining Your App's Icon
    • Migration from MetaMask
  • 🎨Logo Assets
  • 🧙Support
  • 🕹️Trouble Shooting
  • ❤️Contribute
Powered by GitBook
On this page
  • Basic Usage
  • Chain IDs
  • Methods
  • Events
  • Errors

Was this helpful?

Edit on GitHub
  1. Connect To Software
  2. WebApp Connect OneKey
  3. ETH

Provider API

PreviousETHNextRPC API

Last updated 1 year ago

Was this helpful?

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. The presence of the provider object indicates an Ethereum user.

We recommend using typeof window !== 'undefined' && window.$onekey.ethereum to detect our provider in browser.

The Ethereum JavaScript provider API is specified by .

if (typeof window !== 'undefined' && window.$onekey?.ethereum) {  
  // From now on, this should always be true:  
  startApp(provider); // initialize your app
} else {  
  console.log('Please install OneKey Browser Extension at https://onekey.so/download!');
}

Basic Usage

For any non-trivial Ethereum web application — a.k.a. dapp, web3 site etc. — to work, you will have to:

  • Detect the OneKey provider (window.$onekey.ethereum)

  • Detect which Ethereum network the user is connected to

  • Get the user's Ethereum account(s)

The snippet at the top of this page is sufficient for detecting the provider. You can learn how to accomplish the other two by reviewing the snippet in the .

The provider API is all you need to create a full-featured web3 application.

That said, many developers use a convenience library, such as , instead of using the provider directly. If you are in need of higher-level abstractions than those provided by this API, we recommend that you use a convenience library.

Chain IDs

Hex
Decimal
Network

0x1

1

Ethereum Main Network (Mainnet)

0x38

56

Binance Smart Chain (Mainnet)

0x80

128

Huobi Eco Chain (Mainnet)

0x41

65

OEC Mainnet

0x89

137

Matic (Polygon)

0xfa

250

Fantom Main Network

0x64

100

xDai Main Network

0x3

3

Ropsten Testnet

0x2a

42

kovan Testnet

0x4

4

Rinkeby Testnet

Methods

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.

window.$onekey.ethereum.isConnected(): boolean;

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

window.$onekey.ethereum.request(args)

interface RequestArguments {  method: string;  params?: unknown[] | object;}
window.$onekey.ethereum.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>.

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 the OneKey Browser Extension RPC API documentation for details.

Example

params: [  
    {    
        from: '0xb60e8dd61c5d32be8058bb8eb970870f0java7233155',    
        to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567',    
        gas: '0x76c0', // 30400    
        gasPrice: '0x9184e72a000', // 10000000000000    
        value: '0x9184e72a', // 2441406250    
        data:      '0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675',  
     },
 ];
window.$onekey.ethereum.request({    
    method: 'eth_sendTransaction',    
    params,  
}).then((result) => {    
    // The result varies by by RPC method.    
    // For example, this method will return a transaction hash hexadecimal string on success.  
    })  
    .catch((error) => {    
        // If the request fails, the Promise will reject with an error.  
    });

Events

This sections 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;}
window.$onekey.ethereum.on('connect', handler: (connectInfo: ConnectInfo) => void);

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

window.$onekey.ethereum.on('disconnect', handler: (error: ProviderRpcError) => void);

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-restablished, which requires reloading the page. You can also use the window.$onekey.ethereum.isConnected() method to determine if the provider is disconnected.

accountsChanged

window.$onekey.ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);

The OneKey provider emits this event whenever the return value of the eth_accounts RPC method changes. eth_accounts returns an array that is either empty or contains a single account address. The returned address, if any, is the address of the most recently used account that 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.

Tip

We plan to allow the eth_accounts array to be able to contain multiple addresses in the near future.

chainChanged

Tip

window.$onekey.ethereum.on('chainChanged', handler: (chainId: string) => void);

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.

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

message

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

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.

RPC subscription updates are a common use case for the message event.

For example, if you create a subscription using eth_subscribe, each subscription update will be emitted as a message event with a type of eth_subscription.

Errors

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

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

The window.$onekey.ethereum.request(args) method throws errors eagerly.

You can often use the error 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

These are the IDs of the Ethereum chains that OneKey supports by default. Visit for more.

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

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

The OneKey Browser Extension provider implements the API.

See the for OneKey Browser Extension's default chains and their chain IDs.

For the complete list of errors, please see and .

🔮
EIP-1193
Using the Provider section
ethers
chainlist
connect
disconnect
Ethereum RPC Error
Node.js EventEmitter
Chain IDs section
EIP-1193
EIP-1474