I am new to web3 and ethereum blockchain. I tried broadcasting a transaction using the following code but it always gives me an invalid sender error.The sample code is shown below.
JavaScript
x
36
36
1
const Tx = require('ethereumjs-tx').Transaction;
2
3
const Web3 = require('web3');
4
var url = 'https://ropsten.infura.io/v3/XXX';
5
const web3 = new Web3(new Web3.providers.HttpProvider(url));
6
7
8
const account1 = '0xaB7BXXX';
9
web3.eth.defaultAccount = account1;
10
11
12
13
const privatekey1 = Buffer.from('fee069363aXXX','hex');
14
15
16
web3.eth.getTransactionCount(account1, (err, txCount) => {
17
18
data = "0xXXX";
19
const txObject = {
20
nonce: web3.utils.toHex(txCount),
21
gasLimit: web3.utils.toHex(200000),
22
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
23
data: data
24
}
25
const tx = new Tx(txObject)
26
tx.sign(privatekey1)
27
28
const serializedTx = tx.serialize()
29
const raw = '0x' + serializedTx.toString('hex')
30
31
32
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
33
console.log('err:', err, 'txHash:', txHash)
34
})
35
});
36
The error occurs at the below line
JavaScript
1
20
20
1
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
2
console.log('err:', err, 'txHash:', txHash)
3
})
4
});
5
6
ERROR:
7
err: Error: Returned error: invalid sender
8
at Object.ErrorResponse (/home/vishnu/node_modules/web3-core-helpers/src/errors.js:29:16)
9
at /home/vishnu/node_modules/web3-core-requestmanager/src/index.js:140:36
10
at XMLHttpRequest.request.onreadystatechange (/home/vishnu/node_modules/web3-providers-http/src/index.js:96:13)
11
at XMLHttpRequestEventTarget.dispatchEvent (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
12
at XMLHttpRequest._setReadyState (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
13
at XMLHttpRequest._onHttpResponseEnd (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
14
at IncomingMessage.<anonymous> (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
15
at emitNone (events.js:111:20)
16
at IncomingMessage.emit (events.js:208:7)
17
at endReadableNT (_stream_readable.js:1064:12)
18
at _combinedTickCallback (internal/process/next_tick.js:138:11)
19
at process._tickCallback (internal/process/next_tick.js:180:9) txHash: undefined
20
Please help me know how to fix this problem. Thanks.
Advertisement
Answer
You can try changing
const tx = new Tx(txObject);
to
const tx = new Tx(txObject, { chain: 'ropsten' });