wallet_addEthereumChain
请求 UKey Wallet 添加一条新的 EVM 网络。用户确认后,该网络会保存到钱包中;如果网络已存在,钱包可能直接切换到该链。
入参
参数为数组,数组内包含一个链配置对象:
| 字段 | 类别 | 必填 | 说明 |
|---|---|---|---|
chainId | string | 是 | 链 ID,带 0x 前缀的十六进制 |
chainName | string | 是 | 展示给用户的网络名称 |
nativeCurrency | object | 是 | 原生代币信息 |
nativeCurrency.name | string | 是 | 原生代币名称 |
nativeCurrency.symbol | string | 是 | 原生代币符号,通常 2-6 个字符 |
nativeCurrency.decimals | number | 是 | 原生代币精度,通常为 18 |
rpcUrls | string[] | 是 | RPC URL 列表,至少一个 |
blockExplorerUrls | string[] | 否 | 区块浏览器 URL 列表 |
iconUrls | string[] | 否 | 网络图标 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 | 用户取消了本次请求 | 用户取消了添加网络 |
| -32602 | Invalid params | 链配置无效 |
说明
- 钱包通常只使用
rpcUrls和blockExplorerUrls的第一个可用地址。 - 传入 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;
}
}
}