النمط
Connect to Extension Wallet

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.

<button class="connectEthereumButton">Connect Ethereum</button>

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.

<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="addTokenButton btn">Add Token</button>

EIP-5792 Support#

The wallet supports batch sending multiple calls and querying transaction results.

Defined by the EIP-5792 specification.

wallet_sendCalls#

Request the wallet to batch send multiple calls.

Parameters

type Capability = {
  [key: string]: unknown;
  optional?: boolean;
}

type SendCallsParams = {
  version: string;
  id?: string;
  from?: `0x${string}`;
  chainId: `0x${string}`;
  atomicRequired: boolean;
  calls: {
    to?: `0x${string}`;
    data?: `0x${string}`;
    value?: `0x${string}`;
    capabilities?: Record<string, Capability>;
  }[];
  capabilities?: Record<string, Capability>;
};
  • version: Fixed value, "2.0.0"
  • id: Optional, unique identifier for the request. If not provided, the wallet will automatically generate an id
  • from: Optional, the wallet address initiating the request. If not provided, it will be the currently connected wallet
  • chainId: The chain id for initiating the transaction
  • atomicRequired: Whether it must be an atomic transaction. Currently, all transactions sent through OKX are atomic transactions
  • calls: List of batch calls
    • to: The contract address to call
    • data: Transaction data
    • value: Amount of main currency to transfer
    • capabilities: Not currently supported
  • capabilities: Not currently supported

Return Value

type SendCallsResult = {
  id: string;
  capabilities?: Record<string, any>;
};

Usage Example

window.okxwallet.request({
     "method": "wallet_sendCalls",
     "params": [
        {
          version: "2.0.0",
          from: "0x819d3f4c17d50004c165d06f22418c4f28010eda",
          chainId: "0x1",
          atomicRequired: true,
          calls: [
            {
              to: "0x54f1C1965B355e1AB9ec3465616136be35bb5Ff7",
              value: "0x0"
            },
            {
              to: "0x2D48e6f5Ae053e4E918d2be53570961D880905F2",
              value: "0x0"
            }
          ],
        }
      ],
})

wallet_getCallsStatus#

Get the status of transactions previously sent via wallet_sendCalls.

Parameters

// Parameters
type GetCallsParams = [string];

Query transaction by id.

Return Value

type GetCallsResult = {
  version: string;
  id: `0x${string}`;
  chainId: `0x${string}`;
  status: number;
  atomic: boolean;
  receipts?: {
    logs: {
      address: `0x${string}`;
      data: `0x${string}`;
      topics: `0x${string}`[];
    }[];
    status: `0x${string}`;
    blockHash: `0x${string}`;
    blockNumber: `0x${string}`;
    gasUsed: `0x${string}`;
    transactionHash: `0x${string}`;
  }[];
  capabilities?: Record<string, any>;
};
  • version: Version of the sent transaction
  • id: Unique identifier
  • chainId: Chain id where the transaction was initiated
  • status: Transaction status,
    • 100: Confirming
    • 200: Confirmed
    • 400: Off-chain failure
    • 500: Rejected
  • receipts: Detailed transaction information
  • capabilities: Not currently supported

Usage Example

window.okxwallet.request({
     "method": "wallet_getCallsStatus",
     "params": [
       "0x123456"
     ],
})

wallet_getCapabilities#

Returns the wallet's support information for the corresponding atomic functionality.

Parameters

type GetCapabilitiesParams = [`0x${string}`, [`0x${string}`]];
  • The first parameter is the address to query
  • The second parameter is the list of chains to query

Return Value

type GetCapabilitiesResult = Record<`0x${string}`, <Record<string, any>>;

If a chain does not support sending batch transactions, it will not appear in the query results.

Usage Example

window.okxwallet.request({
    "method": "wallet_getCapabilities",
    "params": [
        "0x00b909cefa36ab6bc26f5887a867e46ef162238f0a171b1c2974b665afd4237f",
        [
            "0x1",
            "0xaa36a7"
        ]
    ],
});

// Response example
{
    "0x1": {
        "atomic": {
            "status": "supported"
        }
    },
    "0xaa36a7": {
        "atomic": {
            "status": "ready"
        }
    }
}

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.

<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="switchChainButton btn">Switch Chain</button>