使用Web3签名BEP20代币时Gas价格异常过高的问题排查
问题分析:签名BEP20代币时Gas价格异常过高的原因及修复方案
核心原因
交易字段冲突
代码中同时设置了传统交易的gasPrice字段和EIP-1559交易的maxPriorityFeePerGas/maxFeePerGas字段,两类字段混合会导致交易结构体解析混乱,最终计算出异常超大的Gas价格数值。BSC网络虽兼容EIP-1559,但多数场景下推荐二选一,不能同时配置两类字段。库版本适配问题
你使用的ethereumjs-tx若为旧版本,对EIP-1559字段的支持不完善,混合字段时会出现解析错误,直接导致Gas价格计算异常。
修复方案
方案一:使用传统交易模式(BSC推荐)
移除EIP-1559相关字段,仅保留传统交易参数:
const Tx = require('ethereumjs-tx').Transaction const { Web3 } = require('web3'); const rpcUrl = 'https://bsc-dataseed1.binance.org:443' const web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl)); // 确保gasPriceToEther为合法数值,如'5'代表5gwei const txObject = { nonce: web3.utils.toHex(txCount), // 无需转Number,直接处理 to: addressTo, value: web3.utils.toHex(web3.utils.toWei(balancetoSendToEther, 'ether')), gasLimit: web3.utils.toHex(21000), gasPrice: web3.utils.toHex(web3.utils.toWei(gasPriceToEther, 'gwei')), common: { customChain: { name: 'Binance Smart Chain', chainId: 56, networkId: 56 } } } // 签名交易:私钥需转为Buffer格式 const tx = new Tx(txObject) tx.sign(Buffer.from(_private_key.replace('0x', ''), 'hex')) const serializedTransaction = tx.serialize() const raw = '0x' + serializedTransaction.toString('hex')
方案二:正确使用EIP-1559交易模式
若需使用EIP-1559,需移除gasPrice字段,并确保使用支持EIP-1559的@ethereumjs/tx v3+版本:
const { Transaction } = require('@ethereumjs/tx'); const { Web3 } = require('web3'); const rpcUrl = 'https://bsc-dataseed1.binance.org:443' const web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl)); const txObject = { nonce: web3.utils.toHex(txCount), to: addressTo, value: web3.utils.toHex(web3.utils.toWei(balancetoSendToEther, 'ether')), gasLimit: web3.utils.toHex(21000), maxPriorityFeePerGas: web3.utils.toHex(web3.utils.toWei("3", "gwei")), maxFeePerGas: web3.utils.toHex(web3.utils.toWei("3", "gwei")), type: '0x2', // 明确指定EIP-1559交易类型 chainId: 56 } const tx = Transaction.fromTxData(txObject, { chain: 'bsc' }); tx.sign(Buffer.from(_private_key.replace('0x', ''), 'hex')); const serializedTransaction = tx.serialize() const raw = '0x' + serializedTransaction.toString('hex')
额外注意事项
- 私钥必须转为Buffer格式传入
tx.sign,记得去除开头的0x前缀。 nonce无需转为Number,直接用web3.utils.toHex处理,避免大数精度丢失。- 确认
gasPriceToEther是有效的字符串/数值,若为未定义或错误值,web3.utils.toWei会生成异常结果。
内容的提问来源于stack exchange,提问作者Moutairou
相关产品推荐
相关产品推荐

