切换网络#
wallet_switchEthereumChain
EIP-3326
此方法由 EIP-3326 指定。
描述
此方法询问用户是否要切换到具有指定 chainId
的链上,并返回一个确认值。
与任何确认值出现的场景一样,wallet_switchEthereumChain
只能作为直接用户操作的结果调用,例如用户单击按钮的时候。
欧易会在以下情况下自动拒绝请求:
- 链 ID 格式错误
- 指定链 ID 所属的链尚未添加到欧易
我们建议你与 wallet_addEthereumChain
一起使用:
try {
await okxwallet.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xf00' }],
});
} catch (switchError) {
// This error code indicates that the chain has not been added to OKX.
if (switchError.code === 4902) {
try {
await okxwallet.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0xf00',
chainName: '...',
rpcUrls: ['https://...'] /* ... */,
},
],
});
} catch (addError) {
// handle "add" error
}
}
// handle other "switch" errors
}
参数
-
Array
SwitchEthereumChainParameter
interface SwitchEthereumChainParameter {
chainId: string; // A 0x-prefixed hexadecimal string
}
链 IDs
这些是欧易默认支持的以太坊链的 ID。 更多信息请咨询 chainid.network。
十六进制 | 十进制 | 网络 |
---|---|---|
0x1 | 1 | Ethereum Main Network (Mainnet) |
0x2711 | 10001 | ETHW |
0x42 | 66 | OKT Chain Mainnet |
0x38 | 56 | Binance Smart Chain Mainnet |
0x89 | 137 | Matic Mainnet |
0xa86a | 43114 | Avax Mainnet |
0xfa | 250 | Fantom Mainnet |
0xa4b1 | 42161 | Arbitrum Mainnet |
0xa | 10 | Optimism Mainnet |
0x19 | 25 | Cronos Mainnet |
0x2019 | 8217 | Klaytn Mainnet |
0x141 | 321 | KCC Mainnet |
0x440 | 1088 | Metis Mainnet |
0x120 | 288 | Boba Mainnet |
0x64 | 100 | Gnosis Mainnet |
0x505 | 1285 | Moonriver Mainnet |
0x504 | 1284 | Moonbeam Mainnet |
0x406 | 1030 | Conflux eSpace |
返回值
null
- 如果此方法请求成功,该方法会返回 null
,否则将会返回一个错误值。
如果错误码(error.code
)为 4902
,说明请求的链没有被欧易添加,另需要通过 wallet_addEthereumChain
请求添加。
例子
在 codeopen中打开。
HTML
JavaScript
<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="switchChainButton btn">Switch Chain</button>
const connectEthereumButton = document.querySelector('.connectEthereumButton');
const switchChainButton = document.querySelector('.switchChainButton');
let accounts = [];
//Sending Ethereum to an address
switchChainButton.addEventListener('click', () => {
try {
const chainId = okxwallet.chainId === "0x42" ? "0x38" : "0x42";
await okxwallet.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainId }]
});
} catch (switchError) {
// This error code indicates that the chain has not been added to OKX Wallet.
if (error.code === 4902) {
try {
await okxwallet.request({
method: "wallet_addEthereumChain",
params: [{ chainId: "0xf00", rpcUrl: "https://..." /* ... */ }]
});
} catch (addError) {
// handle "add" error
}
}
// handle other "switch" errors
}
});
connectEthereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
try{
accounts = await okxwallet.request({ method: 'eth_requestAccounts' });
}catch(error){
console.log(error);
}
}