跳到主要内容

wallet_addEthereumChain

请求 UKey Wallet 添加一条新的 EVM 网络。用户确认后,该网络会保存到钱包中;如果网络已存在,钱包可能直接切换到该链。


入参

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

字段类别必填说明
chainIdstring链 ID,带 0x 前缀的十六进制
chainNamestring展示给用户的网络名称
nativeCurrencyobject原生代币信息
nativeCurrency.namestring原生代币名称
nativeCurrency.symbolstring原生代币符号,通常 2-6 个字符
nativeCurrency.decimalsnumber原生代币精度,通常为 18
rpcUrlsstring[]RPC URL 列表,至少一个
blockExplorerUrlsstring[]区块浏览器 URL 列表
iconUrlsstring[]网络图标 URL 列表

结果

成功时返回 null


示范

await window.$ukey.ethereum.request({
method: "wallet_addEthereumChain",
requestParams: [
{
chainId: "0x89",
chainName: "Polygon Mainnet",
nativeCurrency: {
name: "MATIC",
symbol: "MATIC",
decimals: 18,
},
rpcUrls: ["https://polygon-rpc.com"],
blockExplorerUrls: ["https://polygonscan.com"],
},
],
});

添加 Base

await window.$ukey.ethereum.request({
method: "wallet_addEthereumChain",
requestParams: [
{
chainId: "0x2105",
chainName: "Base",
nativeCurrency: {
name: "Ethereum",
symbol: "ETH",
decimals: 18,
},
rpcUrls: ["https://mainnet.base.org"],
blockExplorerUrls: ["https://basescan.org"],
},
],
});

添加 Arbitrum

await window.$ukey.ethereum.request({
method: "wallet_addEthereumChain",
requestParams: [
{
chainId: "0xa4b1",
chainName: "Arbitrum One",
nativeCurrency: {
name: "Ethereum",
symbol: "ETH",
decimals: 18,
},
rpcUrls: ["https://arb1.arbitrum.io/rpc"],
blockExplorerUrls: ["https://arbiscan.io"],
},
],
});

错误码

错误码消息说明
4001用户取消了本次请求用户取消了添加网络
-32602Invalid params链配置无效

说明

  • 钱包通常只使用 rpcUrlsblockExplorerUrls 的第一个可用地址。
  • 传入 RPC 前请确认来源可信,避免引导用户连接恶意节点。
  • 钱包可能会验证 RPC 端点是否能正常响应对应 Chain ID。
  • 某些钱包对非 18 位精度的原生代币支持有限。
  • 遵循 EIP-3085 规范。

组合添加和切换

async function switchOrAddChain(chainConfig) {
try {
await window.$ukey.ethereum.request({
method: "wallet_switchEthereumChain",
requestParams: [{ chainId: chainConfig.chainId }],
});
} catch (error) {
if (error.code === 4902) {
await window.$ukey.ethereum.request({
method: "wallet_addEthereumChain",
requestParams: [chainConfig],
});
} else {
throw error;
}
}
}