通过BEP20网络发送代币时Metamask显示错误代币问题咨询
错误根因
ERC20代币转账本质是调用对应代币合约的transfer方法,因此eth_sendTransaction参数中的to字段必须填写代币合约地址,你代码中该字段误填为收款用户地址reciever,导致Metamask无法匹配到对应代币合约,出现显示异常。
此外你的代码还存在两个潜在风险:
gas字段留空,部分节点或钱包会直接拒绝该交易- 写死的
gasPrice可能因网络波动过低导致交易长时间无法打包
修复代码
调整to字段为代币合约地址,补充动态获取gas参数的逻辑即可,修正后代码如下:
(async ()=>{ const contract = new web3.eth.Contract(ABI, contractAddress); const transfer = await contract.methods.transfer(reciever, 1); const data = await transfer.encodeABI(); if(window.ethereum.chainId == '0x61'){ // 动态估算gas limit与gas price,适配当前网络状态 const gasLimit = await transfer.estimateGas({from: ethereum.selectedAddress}); const gasPrice = await web3.eth.getGasPrice(); ethereum .request({ method: 'eth_sendTransaction', params: [ { from: ethereum.selectedAddress, // 此处修改为代币合约地址,是解决显示错误的核心 to: contractAddress, gasPrice: gasPrice, gas: gasLimit, data: data, }, ], }) .then((txHash) => console.log(txHash)) .catch((error) => console.error); } else { ethereum.request({ method: 'wallet_switchEthereumChain', params:[{chainId: '0x61'}]}) } })()
修改后Metamask会自动识别对应合约信息,正确展示转账的代币名称、数量和收款地址。
内容的提问来源于stack exchange,提问作者Barbara Ketlin
相关产品推荐
相关产品推荐

