web3发交易经常出现invalid sender ,或者Invalid JSON RPC response: {"size":0,"timeout":0}报错,这个报错很不具体,云里雾里。经过我的反复测试,这是和web3相关的包版本有关。
以web3.js发送交易为例,以下两种写法可以发送成功,
一、ethereumjs-tx安装最新版本, web3安装最新版本
var Tx = require('ethereumjs-tx').Transaction
web3.eth.getTransactionCount(config.managerAddress, "pending", (err, txCount) => {
web3.eth.estimateGas({
from: config.managerAddress,
to: toAddress,
data: inByteCode
}, (err, gas) => {
var transaction = {
"nonce": web3.utils.toHex(txCount),
"from": config.managerAddress,
"to": toAddress,
"value": "0x0",
"gasPrice": web3.utils.toHex(10000000000),
"gasLimit": web3.utils.toHex(gas),
"data": inByteCode
}
var web3Account = web3.eth.accounts.privateKeyToAccount(config.managerPrivatekey);
web3Account.signTransaction(transaction, (err, signedTx) => {
web3.eth.sendSignedTransaction(signedTx.rawTransaction, (err,hash) => {
})
}
})
})
})
注意这里不能用以下方式发交易
var tx = new Tx(transaction);
var privateKey = Buffer.from(config.managerPrivatekey,'hex');
tx.sign(privateKey1);
var serializedTx = tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')
否则会出现Invalid JSON RPC response: {"size":0,"timeout":0}异常。
如果想用这种发,则按如下第二种写法:
二、ethereumjs-tx必须为1.3.7版本,web3可以为最新版本
var Tx = require('ethereumjs-tx') //-----注意这里没有.Transaction
web3.eth.getTransactionCount(config.managerAddress, "pending", (err, txCount) => {
web3.eth.estimateGas({
from: config.managerAddress,
to: toAddress,
data: inByteCode
}, (err, gas) => {
var transaction = {
"nonce": web3.utils.toHex(txCount),
"from": config.managerAddress,
"to": toAddress,
"value": "0x0",
"gasPrice": web3.utils.toHex(10000000000),
"gasLimit": web3.utils.toHex(gas),
"data": inByteCode
}
var tx = new Tx(transaction);
var privateKey = Buffer.from(config.managerPrivatekey,'hex');
tx.sign(privateKey);
var serializedTx = tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'),
function(err, hash) {
if (!err){
console.log(hash);
}else{
console.log(err);
}
});
}
})
官方文档里var Tx = require('@ethereumjs/tx').Transaction,这种引用新的版本包我至今还没发成功过。