跳到主要内容

wallet_switchEthereumChain

请求 UKey Wallet 切换到指定 EVM 网络。如果钱包中尚未添加该网络,请先通过 wallet_addEthereumChain 添加。


入参

参数为数组,数组内包含一个对象:

字段类别必填说明
chainIdstring目标链 ID,带 0x 前缀的十六进制

结果

成功时返回 null


示范

try {
await window.$ukey.ethereum.request({
method: "wallet_switchEthereumChain",
requestParams: [{ chainId: "0x89" }], // Polygon 主网
});
console.log("现已切换到 Polygon");
} catch (error) {
if (error.code === 4902) {
// 如果链还没加进钱包,就先尝试补加
await window.$ukey.ethereum.request({
method: "wallet_addEthereumChain",
requestParams: [
{
/* 这里填链配置 */
},
],
});
}
}

常用链 ID

十六进制十进制
Ethereum0x11
Polygon0x89137
BSC0x3856
Arbitrum0xa4b142161
Optimism0xa10
Base0x21058453
Avalanche0xa86a43114

错误码

错误码消息说明
4001用户取消了本次请求用户取消了网络切换
4902无法识别的链 ID钱包里尚未配置该链

说明

  • 如果目标链未配置,会返回 4902,此时可引导用户添加网络。
  • 用户可能需要在钱包中确认切换操作。
  • 切换完成后会触发 chainChanged,请在事件中刷新链相关状态。
  • 遵循 EIP-3326 规范。
window.$ukey.ethereum.on("chainChanged", (chainId) => {
console.log("现已切换到链:", chainId);
// 建议操作:刷新页面
window.location.reload();
});