0

Can anyone help me fix this problem? I get 'txHash: undefined' error in terminal

var Tx = require('ethereumjs-tx').Transaction
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/.....')

const account1 = '0x4e8143b70aC257BC26......................'
const account2 = '0x7184a5934B9B36E210......................'


const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1, 'hex')
const privateKey2 = Buffer.from(process.env.PRIVATE_KEY_2, 'hex')

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

// Build a transaction
const txObject = {
    nonce: web3.utils.toHex(txCount),
    to: account1,
    value: web3.utils.toHex(web3.utils.toWei('1', 'ether')),
    gasLimit: web3.utils.toHex(21000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}

// sign a transaction
const tx = new Tx(txObject)
tx.sign(privateKey2)

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

// Broadcast the transacation

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

As you are connected to the Ropsten testnet you have to change const tx = new Tx(txObject) to const tx = new Tx(txObject, { chain: 'ropsten' }).

Without the { chain: 'ropsten' }, ethereumjs-tx signs a mainnet transaction. Your code does not work because you are basically trying to send a mainnet transaction whereas your web3 provider connects to the Ropsten testnet.

Note that transaction signatures differ from network to network to protect against replay attacks (see What is a replay attack? for more info).

5
  • Thanks for your response and have changed it to 'const tx = new Tx(txObject, { chain: 'ropsten' })' but I'm still getting the same 'txHash: undefined' error. Could there be anything else? – ETHus Feb 21 at 12:06
  • I tried the code and it's working. Therefore make sure your infura provider is correct as well as the private keys. Also private keys must not include the hex prefix '0x' in your .env file. – clement Feb 21 at 12:25
  • Do you have sufficient funds on the sending address (account2) ? Note that you need to hold more than 1 ETH to cover the transaction fee. What you are sending is 1 ETH + 21000*gasPrice. – clement Feb 21 at 16:06
  • Also catching the error adding if(err) {console.log(err)} in the sendSignedTransaction function callback will help. – clement Feb 21 at 16:23
  • 1
    I didn't factor in the gasPrice on the sending address. It works now. Thanks for your help mate :)) – ETHus Feb 21 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.