使用ethers.js发送BEP20 Token时遭遇BigNumber格式错误
解决ethers.js v6发送BEP20代币时的BigNumberish错误
从错误栈可以明确,问题出在gasLimit参数传入了不兼容的BigNumber类型——ethers v6已废弃旧版BigNumber类,改用原生BigInt或数字/字符串类型,以下是具体解决方案:
方案1:显式指定合规的gasLimit
调用transfer时通过overrides参数传入BigInt类型的gasLimit:
const tx = await erc20_rw.transfer(recieverAddress, ethers.parseUnits('10', 18), { gasLimit: BigInt(300000) // BEP20转账通常30万gas足够,可根据实际调整 }); await tx.wait();
也可以用ethers.toBigInt("300000")将字符串转换为BigInt,效果一致。
方案2:排查全局gas配置
若你的provider或钱包设置了默认gasLimit,确保其类型为BigInt、数字或字符串,而非旧版ethers的BigNumber或BN.js对象:
- 修正默认配置示例:
// 调整provider默认gasLimit为BigInt类型 provider.defaultGasLimit = BigInt(300000);
方案3:清理依赖冲突
检查项目是否同时引入ethers v5和v6版本,执行命令:
npm ls ethers
若存在多版本,卸载旧版并重装v6:
npm uninstall ethers@5.x npm install ethers@latest
额外验证
确认ethers.parseUnits返回的是合规类型:
console.log(typeof ethers.parseUnits('10', 18)); // 应输出"bigint"
内容的提问来源于stack exchange,提问作者Gursahb Webcyst
相关产品推荐
相关产品推荐

