wallet_switchEthereumChain
Request UKey Wallet to switch to the specified EVM network. If the network has not been added to your wallet yet, please add it via wallet_addEthereumChain first.
Inputs
Pass an array whose first item is an object:
| Field | Variant | Need | Remarks |
|---|---|---|---|
chainId | string | yes | Target chain ID in 0x-prefixed hex |
return value
Returns null on success.
Demo
try {
await window.$ukey.ethereum.request({
method: "wallet_switchEthereumChain",
requestParams: [{ chainId: "0x89" }], // Note: Polygon
});
console.log("Changed over to Polygon");
} catch (error) {
if (error.code === 4902) {
// If the chain is missing, try adding it first
await window.$ukey.ethereum.request({
method: "wallet_addEthereumChain",
requestParams: [
{
/* Note: Chain configuration */
},
],
});
}
}
Common chain ID
| chain | hexadecimal | decimal |
|---|---|---|
| Ethereum | 0x1 | 1 |
| Polygon | 0x89 | 137 |
| BSC | 0x38 | 56 |
| Arbitrum | 0xa4b1 | 42161 |
| Optimism | 0xa | 10 |
| Base | 0x2105 | 8453 |
| Avalanche | 0xa86a | 43114 |
error code
| Code | Message | Details |
|---|---|---|
| 4001 | User rejected the request | Network switch was rejected by the user |
| 4902 | Chain ID is not recognized | Wallet does not have this network configured |
illustrate
- If the target chain is not configured,
4902will be returned, and the user can be guided to add a network. - Users may need to confirm the switch operation in their wallet.
chainChangedwill be triggered after the switch is completed, please refresh the chain-related status in the event.- Follows EIP-3326 specification.
window.$ukey.ethereum.on("chainChanged", (chainId) => {
console.log("Changed over to chain:", chainId);
// Suggested action: reload the page
window.location.reload();
});