BSC币安智能链 Binance Smart Chain,作为币安链的平行运行链,可实现智能合约创建以及 BNB 质押挖矿等功能。其于2020年4月创建,不仅可以创建代币智能合约,还引入 BNB 形成质押挖矿机制。 BSC 是以太坊虚拟机兼容的区块链,是加密资产行业顶尖项目的测试和前沿探索。
Switch network
下例中仅支持BSC
import Web3 from 'web3'
const BSC_CHAIN_ID = 56
export const changeToBscNetwork = async (
library: any,
onError?: () => void
) => {
try {
await library.provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: Web3.utils.toHex(BSC_CHAIN_ID) }]
})
} catch (error: any) {
if (error.code === 4902) {
try {
library.provider.request({
jsonrpc: '2.0',
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0x38',
chainName: 'Binance Smart Chain Mainnet',
rpcUrls: ['https://bsc-dataseed.binance.org/'],
nativeCurrency: {
name: 'BNB',
symbol: 'BNB',
decimals: 18
},
blockExplorerUrls: ['https://bscscan.com']
}
],
id: 0
})
} catch (e) {
console.error('changeNetwork addEthereumChain error', e)
}
}
onError?.()
console.error('changeNetwork error', error)
}
}
常见 API
wallet_addEthereumChain
添加网络,切换网络时,错误返回 code
为4902时表示该网络未添加,下面以添加 bsc
到钱包网络中为例:
library.provider.request({
jsonrpc: '2.0',
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0x38',
chainName: 'Binance Smart Chain Mainnet',
rpcUrls: ['https://bsc-dataseed.binance.org/'],
nativeCurrency: {
name: 'BNB',
symbol: 'BNB',
decimals: 18
},
blockExplorerUrls: ['https://bscscan.com']
}
],
id: 0
})