使用ethereumjs-tx时触发Invalid type错误的解决求助
解决ethereumjs-tx创建Transaction实例时的"Invalid type"错误
错误原因分析
报错指向nonce的类型问题,结合代码来看,主要存在以下几个问题:
- 数值参数类型不匹配:
web3.eth.getTransactionCount返回十进制数字,但ethereumjs-tx要求交易的数值字段(nonce、gasPrice、gas、value)必须是十六进制字符串或Buffer。 - 字段名拼写错误:交易对象里写的
gasprice不符合规范,正确字段名是gasPrice(大写P)。 - Gas估算方法误用:用
getGasPrice估算gas是错误的,该方法用于获取当前网络gas价格,估算交易所需gas应该用estimateGas。 - 私钥处理不当:如果私钥带
0x前缀,直接转Buffer会解析失败,需要先移除前缀。 - 冗余字段干扰:交易对象中的
from字段无需手动指定,签名后会自动推导出发送地址。
修复后的代码
// ETH转账 const send = async() =>{ // 1、构建转账的参数 // 获取账户交易次数并转为十六进制 const nonce = await web3.eth.getTransactionCount(address.value); const nonceHex = web3.utils.toHex(nonce); // 获取当前网络gas价格并转为十六进制 const gasPrice = await web3.eth.getGasPrice(); const gasPriceHex = web3.utils.toHex(gasPrice); // 转账金额转为wei并转十六进制 const value = web3.utils.toWei('0.01','ether'); const valueHex = web3.utils.toHex(value); // 构造规范的交易对象 const rawTx = { nonce: nonceHex, gasPrice: gasPriceHex, to: '0x0015B5D608CC1422Fef0ffbAA93a8A8dAC2D1b2b', value: valueHex, data: '0x0000', }; // 2、生成serializedTx // 处理私钥:自动移除0x前缀后转Buffer const priKeyStr = privateKey.value.startsWith('0x') ? privateKey.value.slice(2) : privateKey.value; const priKey = Buffer.from(priKeyStr, 'hex'); // 估算交易所需gas并转为十六进制 const gas = await web3.eth.estimateGas(rawTx); rawTx.gas = web3.utils.toHex(gas); // 创建Transaction实例并签名 const tx = new Tx(rawTx); tx.sign(priKey); // 生成序列化交易数据 const serializedTx = tx.serialize(); // 3、发起转账 const trans = web3.eth.sendSignedTransaction("0x" + serializedTx.toString("hex")); // 监听交易结果 trans.on('transactionHash',(txid)=>{ console.log("交易ID",txid); console.log(`https://goerli.etherscan.io/tx/${txid}`); }); };
关键修改说明
- 所有数值字段(nonce、gasPrice、gas、value)都通过
web3.utils.toHex()转为十六进制字符串,匹配ethereumjs-tx的参数要求。 - 修正
gasprice为规范字段名gasPrice。 - 替换错误的gas估算方法,用
estimateGas正确计算交易所需gas。 - 增加私钥前缀判断逻辑,确保Buffer转换的正确性。
- 移除冗余的
from字段,避免干扰交易构造。 - 修复交易链接的模板字符串语法错误,确保变量能正常解析。
内容的提问来源于stack exchange,提问作者mnbvcxzz1375
相关产品推荐
相关产品推荐

