0
votes

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.

const Tx = require('ethereumjs-tx').Transaction;

const Web3 = require('web3');
var url = 'https://ropsten.infura.io/v3/XXX';
const web3 = new Web3(new Web3.providers.HttpProvider(url));


const account1 = '0xaB7BXXX';
web3.eth.defaultAccount =  account1;



const privatekey1 = Buffer.from('fee069363aXXX','hex');


web3.eth.getTransactionCount(account1, (err, txCount) => {

        data = "0xXXX";
        const txObject = {
            nonce:    web3.utils.toHex(txCount),
            gasLimit: web3.utils.toHex(200000), 
            gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
            data: data
                 }
        const tx = new Tx(txObject)
        tx.sign(privatekey1)

        const serializedTx = tx.serialize()
        const raw = '0x' + serializedTx.toString('hex')


        web3.eth.sendSignedTransaction(raw, (err, txHash) => {
            console.log('err:', err, 'txHash:', txHash)
        })
    });

The error occurs at the below line

web3.eth.sendSignedTransaction(raw, (err, txHash) => {
            console.log('err:', err, 'txHash:', txHash)
        })
    });

ERROR: err: Error: Returned error: invalid sender at Object.ErrorResponse (/home/vishnu/node_modules/web3-core-helpers/src/errors.js:29:16) at /home/vishnu/node_modules/web3-core-requestmanager/src/index.js:140:36 at XMLHttpRequest.request.onreadystatechange (/home/vishnu/node_modules/web3-providers-http/src/index.js:96:13) at XMLHttpRequestEventTarget.dispatchEvent (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22) at XMLHttpRequest._setReadyState (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14) at XMLHttpRequest._onHttpResponseEnd (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14) at IncomingMessage. (/home/vishnu/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61) at emitNone (events.js:111:20) at IncomingMessage.emit (events.js:208:7) at endReadableNT (_stream_readable.js:1064:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9) txHash: undefined

Please help me know how to fix this problem. Thanks.

2
Where you able to resolve this? @pacmanAbel Agoi

2 Answers

1
votes

You can try changing const tx = new Tx(txObject); to const tx = new Tx(txObject, { chain: 'ropsten' });

-2
votes

Did you create your account before using it? Because you are using a hardcoded account address. Same thing for the private Key. Usually you should somehow extract it from the account and not provide it as hardcoded plaintext.