Sending raw transaction

Victor Yeo
1 min readNov 13, 2021

--

In this article, we dissect the ReactJS code to send a raw transaction on Ethereum blockchain or Binance smart chain. The web3 library is used to send the raw transaction.

The steps are:

  1. Specify the gas price and gas limit
  2. Set the txOptions and (for bsc) custom chain info
  3. Create the transaction object
  4. Convert the private key to buffer array
  5. Sign the transaction with the private key
  6. Serialize the transaction to become raw transaction
  7. Send the raw transaction using web3 sendSignedTransaction

When converting the private key to buffer array, make sure to remove the ‘0x’ hex indicator by calling substring function.

privateKey.substring(2,66)

The full code as below:

// sending a raw transaction
let gasPrice = web3.utils.toHex(web3.utils.toWei('100', 'gwei'))
var gasLimit = 21000

var txOptions = {
"nonce": web3.utils.toHex(txCount),
"from": senderAddr,
"to": payeeAddr,
"gasPrice": gasPrice,
"gasLimit": web3.utils.toHex(gasLimit),
"data": hexData,
}

const customCommon = Common.forCustomChain('mainnet', {
name: 'bnb',
networkId: 56,
chainId: 56
}, 'petersburg')

const tx = new Transaction(txOptions, {common: customCommon})
const privateKey = pk

// convert the private key to buffer array
const privateKeyBuff = new Buffer(
privateKey.substring(2,66),
// example private key without the 0x
'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109',
'hex',
)
console.log(privateKeyBuff)
tx.sign(privateKeyBuff)

const serializedTrans = tx.serialize()
const raw = '0x' + serializedTrans.toString('hex')
console.log(raw)

const txHash = await web3.eth.sendSignedTransaction(raw)
console.log('txHash:', txHash)
// end of sending a raw transaction

Hope it helps.

--

--

No responses yet