web3.js调用合约转账时报错overflow out of gas

最近在使用web3.js为BSC开发DAPP,调用合约的transfer方法偶尔会报错。

合约的decimals是18,当transfer较小的数量时,比如999及以下的没问题,1000时就会报错,报错信息有点模糊,有时会报错overflow,有时会报错如下

Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced

这段话是说可能存在如下问题

  1. gas不够
  2. ABI错误
  3. 合约未部署

因为只有大额转账时才会出现,所以上述三种问题都不存在,应该是在传参时没有正确把数量传过去。

通过控制台打印日志,发现发送1000时实际传的是1e+21,成科学计数法了,而web3.js中使用的是BigNumber,传个BigInt过去是不是就可以了呢?

改下代码,最终效果如下

let num = 1000 * Math.pow(10,this.contractDecimals);
num = BigInt(num);
this.contract.methods.transfer(this.toAddress, num).send({from: this.walletAddress}), function(error, transactionHash){
    if(!error) {
        console.log(transactionHash);
    } else {
        console.log(error);
    }
};

重新编译代码,刷新页面,这下能顺利调起钱包支付页面,问题解决!

PS:BigInt是JavaScript内置对象,无需引用!

Leave a Comment

豫ICP备19001387号-1