0

I am trying to send ether from one address to another. After executing the code I am receiving an error: Cannot read property 'then' of undefined. How can I fix this? Thanks in advance.

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


const addressFrom = 'addr1'
const privateKey = Buffer.from('key', 'hex')
const addressTo = 'addr2'


const txData = {
  gasLimit: web3.utils.toHex(25000),
  gasPrice: web3.utils.toHex(10e9), 
  to: addressTo,
  from: addressFrom,
  value: web3.utils.toHex(web3.utils.toWei('0.0002', 'ether')) 
}


function sendRawTransaction(txData){
  web3.eth.getTransactionCount(addressFrom).then(txCount => {
    const newNonce = web3.utils.toHex(txCount)
    const transaction = new Tx({ ...txData, nonce: newNonce }, { chain: 'mainnet' }) 
    transaction.sign(privateKey)
    const serializedTx = transaction.serialize().toString('hex')
    return web3.eth.sendSignedTransaction('0x' + serializedTx)
  })
}

sendRawTransaction(txData).then(result =>
  result
    .on('transactionHash', txHash => {
      console.log('transactionHash:', txHash)
    })
    .on('receipt', receipt => {
      console.log('receipt:', receipt)
    })
    .on('confirmation', (confirmationNumber, receipt) => {
      if (confirmationNumber >= 1) {
        console.log('confirmations:', confirmationNumber, receipt)
      }
    })
    .on('error:', error => {
      console.error(error)
    })
)
2
  • Can anyone help?
    – TaoBao
    Commented Dec 4, 2019 at 22:12
  • The function sendRawTransaction doesn't have a return statement so it will act like it returned undefined. Try adding return before web3.eth.GetTransactionCount(..).
    – Ismael
    Commented Dec 5, 2019 at 15:03

1 Answer 1

0

Try this:

web3.eth.getTransactionCount(addressFrom).then(txCount => {
    const newNonce = web3.utils.toHex(txCount)
    const transaction = new Tx({ ...txData, nonce: newNonce }, { chain: 'mainnet' }) 
    transaction.sign(privateKey)
    const serializedTx = transaction.serialize().toString('hex')
    web3.eth.sendSignedTransaction('0x' + serializedTx)    
    .on('transactionHash', txHash => {
        console.log('transactionHash:', txHash)
    })
    .on('receipt', receipt => {
        console.log('receipt:', receipt)
    })
    .on('confirmation', (confirmationNumber, receipt) => {
        if (confirmationNumber >= 1)
            console.log('confirmations:', confirmationNumber, receipt)
    })
    .on('error:', error => {
        console.error(error)
    })
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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