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
  • RPC API
  • Ethereum JSON-RPC Methods
  • Permissions
  • Other RPC Methods

Was this helpful?

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

RPC API

PreviousProvider APINextAccessing Accounts

Last updated 1 year ago

Was this helpful?

RPC API

OneKey uses the window.$onekey.ethereum.request(args) method to wrap an RPC API.

The API is based on an interface exposed by all Ethereum clients, along with a growing number of methods that may or may not be supported by other wallets.

Tip

All RPC method requests can return errors. Make sure to handle errors for every call to window.$onekey.ethereum.request(args).

Ethereum JSON-RPC Methods

For the Ethereum JSON-RPC API, please see .

Important methods from this API include:

Permissions

Currently, the only permission is eth_accounts, which allows you to access the user's Ethereum address(es). More permissions will be added in the future.

Under the hood, permissions are plain, JSON-compatible objects, with a number of fields that are mostly used internally by OneKey. The following interface lists the fields that may be of interest to consumers:

interface Web3WalletPermission {  
  // The name of the method corresponding to the permission  parentCapability: string;
  // The date the permission was granted, in UNIX epoch time  
  date?: number;
}

eth_requestAccounts

EIP-1102

Returns

string[] - An array of a single, hexadecimal Ethereum address string.

Description

Requests that the user provides an Ethereum address to be identified by. Returns a Promise that resolves to an array of a single Ethereum address string. If the user denies the request, the Promise will reject with a 4001 error.

The request causes a OneKey popup to appear. You should only request the user's accounts in response to user action, such as a button click. You should always disable the button that caused the request to be dispatched, while the request is still pending.

If you can't retrieve the user's account(s), you should encourage the user to initiate an account request.

Example

document.getElementById('connectButton', connect);
function connect() {  
    window.$onekey.ethereum.request({ method: 'eth_requestAccounts' })
        .then(handleAccountsChanged)
        .catch((error) => {      
            if (error.code === 4001) {        
                // EIP-1193 userRejectedRequest error        
                console.log('Please connect to OneKey.');      
            } else {        
                console.error(error);      
            }    
        });
}

wallet_getPermissions

Platform Availability

This RPC method is not yet available in OneKey Mobile.

Returns

Web3WalletPermission[] - An array of the caller's permissions.

Description

Gets the caller's current permissions. Returns a Promise that resolves to an array of Web3WalletPermission objects. If the caller has no permissions, the array will be empty.

wallet_requestPermissions

Platform Availability

This RPC method is not yet available in OneKey Mobile.

Parameters

  • Array

    1. RequestedPermissions - The requested permissions.

interface RequestedPermissions {  [methodName: string]: {}; // an empty object, for future extensibility}

Returns

Web3WalletPermission[] - An array of the caller's permissions.

Description

Requests the given permissions from the user. Returns a Promise that resolves to a non-empty array of Web3WalletPermission objects, corresponding to the caller's current permissions. If the user denies the request, the Promise will reject with a 4001 error.

The request causes a OneKey popup to appear. You should only request permissions in response to user action, such as a button click.

Example

document.getElementById('requestPermissionsButton', requestPermissions);
function requestPermissions() {  
    window.$onekey.ethereum.request({      
        method: 'wallet_requestPermissions',      
        params: [{ eth_accounts: {} }],    
    })    
    .then((permissions) => {      
        const accountsPermission = permissions.find(        
            (permission) => permission.parentCapability === 'eth_accounts'      
        );      
        if (accountsPermission) {        
            console.log('eth_accounts permission successfully requested!');      
        }    
    })    
    .catch((error) => {      
        if (error.code === 4001) {        
            // EIP-1193 userRejectedRequest error        
            console.log('Permissions needed to continue.');      
        } else {        
            console.error(error);      
        }    
    });
}

Other RPC Methods

eth_decrypt

Platform Availability

This RPC method is not yet available in OneKey Mobile.

Parameters

  • Array

    1. string - An encrypted message.

    2. string - The address of the Ethereum account that can decrypt the message.

Returns

string - The decrypted message.

Description

Requests that OneKey decrypts the given encrypted message. The message must have been encrypted using the public encryption key of the given Ethereum address. Returns a Promise that resolves to the decrypted message, or rejects if the decryption attempt fails.

Example

window.$onekey.ethereum.request({    
    method: 'eth_decrypt',    
    params: [encryptedMessage, accounts[0]],  
})
.then((decryptedMessage) =>    console.log('The decrypted message is:', decryptedMessage)  )
.catch((error) => console.log(error.message));

eth_getEncryptionPublicKey

Platform Availability

This RPC method is not yet available in OneKey Mobile.

Parameters

  • Array

    1. string - The address of the Ethereum account whose encryption key should be retrieved.

Returns

string - The public encryption key of the specified Ethereum account.

Description

Requests that the user shares their public encryption key. Returns a Promise that resolve to the public encryption key, or rejects if the user denied the request.

Example

let encryptionPublicKey;
window.$onekey.ethereum.request({    
    method: 'eth_getEncryptionPublicKey',    
    params: [accounts[0]], 
    // you must have access to the specified account  
})  
.then((result) => {    encryptionPublicKey = result;  })  
.catch((error) => {    
    if (error.code === 4001) {      
        // EIP-1193 userRejectedRequest error      
        console.log("We can't encrypt anything without the key.");    
    } else {      
        console.error(error);    
    }  
});

Encrypting

const ethUtil = require('ethereumjs-util');
const encryptedMessage = ethUtil.bufferToHex(  Buffer.from(    JSON.stringify(      sigUtil.encrypt(        encryptionPublicKey,        { data: 'Hello world!' },        'x25519-xsalsa20-poly1305'      )    ),    'utf8'  ));

wallet_addEthereumChain

EIP-3085

Parameters

  • Array

    1. AddEthereumChainParameter - Metadata about the chain that will be added to OneKey.

For the rpcUrls and blockExplorerUrls arrays, at least one element is required, and only the first element will be used.

interface AddEthereumChainParameter {  chainId: string; // A 0x-prefixed hexadecimal string  chainName: string;  nativeCurrency: {    name: string;    symbol: string; // 2-6 characters long    decimals: 18;  };  rpcUrls: string[];  blockExplorerUrls?: string[];  iconUrls?: string[]; // Currently ignored.}

Returns

null - The method returns null if the request was successful, and an error otherwise.

Description

Creates a confirmation asking the user to add the specified chain to OneKey. The user may choose to switch to the chain once it has been added.

As with any method that causes a confirmation to appear, wallet_addEthereumChain should only be called as a result of direct user action, such as the click of a button.

OneKey stringently validates the parameters for this method, and will reject the request if any parameter is incorrectly formatted. In addition, OneKey will reject the request under the following circumstances:

  • If the RPC endpoint doesn't respond to RPC calls.

  • If the RPC endpoint returns a different chain ID when eth_chainId is called.

  • If the chain ID corresponds to any default OneKey chains.

OneKey does not yet support chains with native currencies that do not have 18 decimals, but may do so in the future.

OneKey introduced Web3 Wallet Permissions via . In this permissions system, each RPC method is either restricted or open. If a method is restricted, an external domain (like a web3 site) must have the corresponding permission in order to call it. Open methods, meanwhile, do not require permissions to call, but may require confirmation by the user in order to succeed (e.g. eth_sendTransaction).

The permissions system is implemented in the . If you're interested in learning more about the theory behind this capability-inspired permissions system, we encourage you to take a look at .

This method is specified by . It is equivalent to the deprecated onekey.enable() provider API method.

Under the hood, it calls for the eth_accounts permission. Since eth_accounts is currently the only permission, this method is all you need for now.

See for more information.

The public key is computed from entropy associated with the specified user account, using the implementation of the X25519_XSalsa20_Poly1305 algorithm.

The point of the encryption key is of course to encrypt things. Here's an example of how to encrypt a message using :

This method is specified by .

🔮
the Ethereum wiki
eth_accounts
eth_call
eth_getBalance
eth_sendTransaction
eth_sign
EIP-2255
rpc-cap package
EIP-2255
EIP-1102
eth_getEncryptionPublicKey
nacl
eth-sig-util
EIP-3085
wallet_requestPermissions