// 网络配置
const INJECTIVE_MAINNET_CONFIG = {
chainId: '0x6f0', // 十进制 1776
chainName: 'Injective',
rpcUrls: ['https://evm-rpc.injective.network'],
nativeCurrency: {
name: 'Injective',
symbol: 'INJ',
decimals: 18
},
blockExplorerUrls: ['https://explorer.injective.network']
};
async function addInjectiveNetwork() {
// 检查是否安装了 MetaMask 或其他 Web3 钱包
if (!window.ethereum) {
alert('Please install MetaMask or another Web3 wallet!');
return;
}
try {
// 首先,尝试切换到 Injective 网络
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: INJECTIVE_MAINNET_CONFIG.chainId }],
});
console.log('Switched to Injective network successfully!');
} catch (switchError) {
// 错误代码 4902 表示网络尚未添加
if (switchError.code === 4902) {
try {
// 添加 Injective 网络
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [INJECTIVE_MAINNET_CONFIG],
});
console.log('Injective network added successfully!');
} catch (addError) {
console.error('Failed to add Injective network:', addError);
alert('Failed to add Injective network. Please try again.');
}
} else {
console.error('Failed to switch network:', switchError);
alert('Failed to switch to Injective network.');
}
}
}