EIP-3085 · Stagnant(停滞) · Interface · 2020-11-01
EIP-3085: wallet_addEthereumChain RPC Method
wallet_addEthereumChain RPC 方法让 dapp 请求钱包添加一条 EVM 链(链 ID、RPC URL、货币、浏览器),由用户批准该请求。
它解决什么问题?
部署在 L2 或侧链上的 dapp 需要用户的钱包认识该网络。没有标准时,用户必须手动把链 ID、RPC URL 和货币符号复制到钱包设置中,既容易出错,也容易被钓鱼。
ERC-3085 定义了一个位于 wallet 命名空间的方法,网站可以调用它来建议一条链。钱包会验证数据并展示给用户,只有用户批准才会添加该链。
它如何运作
wallet_addEthereumChain 接受一个对象:
interface AddEthereumChainParameter {
chainId: string; // hex string, e.g. "0xa"
chainName?: string;
rpcUrls?: string[];
nativeCurrency?: { name: string; symbol: string; decimals: number };
blockExplorerUrls?: string[];
iconUrls?: string[];
}
规范中的关键规则:
- 类型上只有
chainId是必填的,但如果rpcUrls缺失或为空,或者chainId与从这些 RPC URL 通过eth_chainId返回的值不一致,钱包必须拒绝该请求。 - URL 必须有效,且不得使用
http:或file:。 - 如果提供了
nativeCurrency,则三个字段都是必填的。 - 成功时返回
null,否则返回错误。钱包可以出于任何原因拒绝。 - 添加一条链并不意味着它会被选中。重新添加一条已存在的链应当成功(除非用户拒绝),并且同一个链 ID 不得被添加两次。
示例代码
通过 EIP-1193 provider 添加一条链,然后切换到它:
const params = {
chainId: "0xa", // 10
chainName: "OP Mainnet",
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: ["https://mainnet.optimism.io"],
blockExplorerUrls: ["https://optimistic.etherscan.io"],
};
try {
await window.ethereum.request({ method: "wallet_addEthereumChain", params: [params] });
// Adding does not select it; ask to switch explicitly (EIP-3326)
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: params.chainId }],
});
} catch (err: any) {
if (err.code === 4001) console.log("user rejected");
else throw err;
}