Search code examples
javascriptethereumweb3js

Web3js signTransation


I am following the documentation to be able to sign and send a transaction on the Kovan testnet. I am currently getting an undefined value when I console out the txHash.

web3.eth.getTransactionCount(account1, (err, txCount) => {
    // 1)Build Transaction
    const txObject = {
        nonce: web3.utils.toHex(txCount),
        to: account2,
        value: web3.utils.toHex(web3.utils.toWei('0.05', 'ether')),
        gasLimit: web3.utils.toHex(2100),
        gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
    }
    
     // 2)Sign Transaction
    const tx = new Tx(txObject,{'chain':42})
    tx.sign(privateKey1)
    
    const serializedTransaction = tx.serialize()
    const raw = '0x' + serializedTransaction.toString('hex')

    console.log("raw:", raw)
    console.log("tx:", serializedTransaction)

    // 3)Broadcast Transaction
    web3.eth.sendSignedTransaction(raw, (err, txHash) =>{
        console.log('txHash:', txHash)
    })
    // COMMENTED-OUT web3.eth.sendSignedTransaction('0x' + serializedTransaction .toString('hex'))
    // .on('receipt', console.log);
})

Solution

  • signTransaction() only performs the signature. It doesn't broadcast the (signed) transaction to the network.

    For that, you can use sendSignedTransaction() (docs), which submits the (signed and serialized) tx data to the provider, and the provider broadcasts it to the network.

    web3.eth.sendSignedTransaction(signedTx.rawTransaction)
    .on('receipt', console.log);