Connect DApp to OKX Wallet
Provider API

Provider API#

What is injected provider API?#

The OKX injected provider API is a JavaScript API that OKX injects into websites visited by our users. Your DApp can use this API to request users' accounts, read data from blockchains users are connected to, and help users sign messages and transactions.

Connecting to your wallet#

eth_requestAccounts

EIP-1102
This method is detailed in EIP-1102. Under the hood, it calls wallet_requestPermissions to gain the eth_accounts permission. Since eth_accounts is currently the only permission, this method is all you need for now.

Description

This request asks the target user to provide an Ethereum address to be identified by. The return value would be a Promise which could be parsed as an array of a single Ethereum address string. If the user denies the request, the Promise will be rejected, returning 4001 error.

The request will cause an OKX popup to appear. You should only request the user's account in response to a direct user action, such as a button click. You should always disable the button that dispatches this request while the previous request is still pending.

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

Return value

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

Example

Open in codeopen.

HTML
JavaScript
<button class="connectEthereumButton">Connect Ethereum</button>
const connectEthereumButton = document.querySelector('.connectEthereumButton');

connectEthereumButton.addEventListener('click', () => {
  //Will Start the OKX extension
  okxwallet.request({ method: 'eth_requestAccounts' });
});

Signing messages#

eth_sign

Description

The signing method will calculate the Ethereum-specific signature: sign (keccak256 (" x19Ethereum Signed Message: n"+len (message)+message)).

By adding a prefix to the message, the calculated signature can be identified as an Ethereum-specific signature. This can prevent malicious decentralized applications from signing arbitrary data (such as transactions) and using signatures to impersonate victims.

Note: The address to be signed must be unlocked.

Parameters

  1. DATA, 20 bytes - address
  2. DATA, N bytes - message to be signed
{
  params:["0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "0xdeadbeaf"],
}

Return value

DATA: signature

{
  result: "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b"
}

Example

Open in codeopen.

HTML
JavaScript
<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="signMessageButton btn">Sign Message</button>
const connectEthereumButton = document.querySelector('.connectEthereumButton');
const signMessageButton = document.querySelector('.signMessageButton');

let accounts = [];

signMessageButton.addEventListener('click', () => {
  okxwallet
    .request({
      method: 'eth_sign',
      params: [account[0], "0xdeadbeaf"],
    })
    .then((res) => console.log(res))
    .catch((error) => console.error);
});

connectEthereumButton.addEventListener('click', () => {
  getAccount();
});

async function getAccount() {
  try{
    accounts = await okxwallet.request({ method: 'eth_requestAccounts' });
  }catch(error){
    console.log(error);
  }
}

Adding token#

Note: This function is only supported on the OKX browser extension.

wallet_watchAsset#

EIP-747
This method is specified in EIP-747.

Description

This requests the user to track a token in OKX Wallet. It'll return a boolean indicating if the token was successfully added.

Most Ethereum wallets support a certain set of tokens, which usually comes from a centrally curated registry of tokens. wallet_watchAsset enables Web3 application developers to ask their users to track tokens in their wallets at runtime.

Once added, the token is indistinguishable from those added via legacy methods, such as a centralized registry.

Parameters

  • WatchAssetParams - The metadata of the asset to watch.
interface WatchAssetParams {
  type: 'ERC20'; // In the future, other standards will be supported
  options: {
    address: string; // The address of the token contract
    'symbol': string; // A ticker symbol or shorthand, up to 11 characters
    decimals: number; // The number of token decimals
    image: string; // A string url of the token logo
  };
}

Return value

boolean - true if the token was added, otherwise, false.

Example

Open in codeopen.

HTML
JavaScript
<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="addTokenButton btn">Add Token</button>
const ethereumButton = document.querySelector('.connectEthereumButton');
const addTokenButton = document.querySelector('.addTokenButton');

addTokenButton.addEventListener('click', () => {
  okxwallet
    .request({
      method: 'wallet_watchAsset',
      params: {
        type: 'ERC20',
        options: {
          address: '0xb60e8dd61c5d32be8058bb8eb970870f07233155',
          symbol: 'FOO',
          decimals: 18,
          image: 'https://foo.io/token-image.svg',
        },
      },
    })
    .then((success) => {
      if (success) {
        console.log('FOO successfully added to wallet!');
      } else {
        throw new Error('Something went wrong.');
      }
    })
    .catch(console.error);
});

ethereumButton.addEventListener('click', () => {
  getAccount();
});

function getAccount() {
  okxwallet.request({ method: 'eth_requestAccounts' }).catch((error)=>{
    console.log(error);
  });
}

Events#

OKX's providers have implemented the Node.js EventEmitter API. This section details the events emitted via that API. There are innumerable EventEmitter guides on the internet, but for this documentation, you can listen to events such as:

okxwallet.on('accountsChanged', (accounts) => {
  // Handle the new accounts, or lack thereof.
  // "accounts" will always be an array, but it can be empty.
});

okxwallet.on('chainChanged', (chainId) => {
  // Handle the new chain.
  // Correctly handling chain changes can be complicated.
  // We recommend reloading the page unless you have a very good reason not to.
  window.location.reload();
});

Also, don't forget to remove listeners once you are done listening to them (for example, when unmounting a component in React):

function handleAccountsChanged(accounts) {
  // ...
}

okxwallet.on('accountsChanged', handleAccountsChanged);

// Later
okxwallet.removeListener('accountsChanged', handleAccountsChanged);

The first argument of the okxwallet.removeListener is the event name and the second argument is the reference to the same function, which has passed to okxwallet.on for the event name mentioned in the first argument.

connect

interface ConnectInfo {
  chainId: string;
}

okxwallet.on('connect', handler: (connectInfo: ConnectInfo) => void);

OKX's providers will emit this event when they can submit RPC requests to the chain for the first time. We recommend using a connect event handler and okxwallet.isConnected() to confirm if OKX Wallet is connected.

disconnect

okxwallet.on('disconnect', handler: (error: ProviderRpcError) => void);

OKX's providers will emit this event if they can't submit RPC requests to the chain. Usually, this only occurs in the case of network connection issues or certain other unforeseeable error states.

Once disconnect has been emitted, the provider won't accept any new requests until the connection to the chain has been re-established, which requires reloading the page. You can also use okxwallet.isConnected() to confirm if OKX Wallet is disconnected.

accountsChanged

okxwallet.on('accountsChanged', handler: (accounts: Array<string>) => void);

OKX's providers will emit this event whenever the return value of the eth_accounts RPC changes. eth_accounts returns an array that either is 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 also 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
See the Chain IDs section for OKX's default chains and their chain IDs.

OKX's providers will emit 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 to this event.

We strongly recommend reloading the page on chain changes, unless you have good reasons not to.

okxwallet.on('chainChanged', (_chainId) => window.location.reload());

message

interface ProviderMessage {
  type: string;
  data: unknown;
}

okxwallet.on('message', handler: (message: ProviderMessage) => void);

OKX's providers will emit this event when there are messages that users should be notified of. The type 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.

Example

Open in codeopen.

HTML
JavaScript
<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="switchChainButton btn">Switch Chain</button>
const ethereumButton = document.querySelector(".connectEthereumButton");
const switchChainButton = document.querySelector(".switchChainButton");

window.okxwallet.on("chainChanged", (_chainId) => {
  console.log(`on chainChanged, current chainId: ${_chainId}`);
});

switchChainButton.addEventListener("click", async () => {
  try {
    await okxwallet.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: okxwallet.chainId === "0x42" ? "0x38" : "0x42" }]
    });
  } catch (error) {
    // handle other "switch" errors
    console.log(error);
  }
});

ethereumButton.addEventListener("click", () => {
  getAccount();
});

async function getAccount() {
  await okxwallet.request({ method: "eth_requestAccounts" });
}