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
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>
const connectEthereumButton = document.querySelector('.connectEthereumButton');
connectEthereumButton.addEventListener('click', () => {
//Will Start the OKX extension
okxwallet.request({ method: 'eth_requestAccounts' });
});
Adding token#
Note: This function is only supported on the OKX browser extension.
wallet_watchAsset
#
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>
const ethereumButton = document.querySelector('.connectEthereumButton');
const addTokenButton = document.querySelector('.addTokenButton');
addTokenButton.addEventListener('click', async () => {
await okxwallet.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x1' }] });
okxwallet
.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: {
address: '0xdac17f958d2ee523a2206206994597c13d831ec7',
symbol: 'USDT',
decimals: 6,
image: 'https://foo.io/token-image.svg',
},
},
})
.then((success) => {
if (success) {
console.log('USDT 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.
eth_accounts
array to be able to contain multiple addresses in the near future.chainChanged
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>
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" });
}