主网和代币管理
跟踪用户的网络链 ID 非常重要,因为所有 RPC 请求都将提交到当前连接的网络。使用 eth_chainId RPC 方法检测用户当前网络的链 ID。
以 ETH 链为例,监听 chainChanged 提供者事件以检测用户何时更改网络:
const chainId = await provider.request({ method: 'eth_chainId' })
provider.on('chainChanged', handleChainChanged)
function handleChainChanged(chainId) {
// 我们建议重新加载页面,除非您必须这样做。
window.location.reload()
}
确定支持的主网支持的典型方法:
- 调用钱包方法切换到目标链。
- 如果切换失败,则表示该链不存在。
例如,切换到 ETH 链的代码为:
try {
await provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xf00' }],
})
} catch (switchError) {
// 此错误代码表示该链尚未添加到MetaMask。
if (switchError.code === 4902) {
try {
await provider.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0xf00',
chainName: '...',
rpcUrls: ['https://...'] /* ... */,
},
],
})
} catch (addError) {
// 处理"添加"错误。
}
}
// 处理其他"切换"错误。
}
添加主网
-
使用钱包的主网添加功能:如何添加/切换主网?
-
通过代码添加主网
// 要添加的主网信息
let chainInfo = {
chainId: '0xaa36a7', // 带0x前缀的十六进制字符串
chainName: 'sepolia',
nativeCurrency: 'ETH',
iconUrls: 'xxx',
rpcUrls: ['https://sepolia.drpc.org'],
blockExplorerUrls: ['https://sepolia.drpc.org'],
nativeCurrency: {
name: 'ETH',
symbol: 'ETH',
decimals: 18,
},
}
await provider.request({
method: 'wallet_addEthereumChain',
params: [chainInfo],
})
什么是代币?
代币是智能合约平台(如以太坊)上的特殊费用载体,用户可以在其中创建、发行和管理代币(主区块链的衍生品)。
添加代币
- 代币余额检查和交易参考 智能合约
const customTokenInfo = {
type: 'ERC20',
options: {
address: '0xd00981105....fe7e037d935b513',
symbol: 'BWB',
decimals: 18,
image: 'http://...',
},
}
const added = await provider.request({
method: 'wallet_watchAsset',
params: customTokenInfo,
})
相关阅读
Last updated on