Skip to content

Instantly share code, notes, and snippets.

@achiko
Forked from raineorshine/sendRawTransaction.js
Created November 15, 2019 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achiko/a1e3a8e29c880408f9d267ed94633fb2 to your computer and use it in GitHub Desktop.
Save achiko/a1e3a8e29c880408f9d267ed94633fb2 to your computer and use it in GitHub Desktop.
Sends a raw transaction with web3 v1.2.2, ethereumjs-tx v2.1.1, and Infura
const Web3 = require('web3')
const Tx = require('ethereumjs-tx').Transaction
// connect to Infura node
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/INFURA_KEY'))
// the address that will send the test transaction
const addressFrom = '0x1889EF49cDBaad420EB4D6f04066CA4093088Bbd'
const privateKey = new Buffer('PRIVATE_KEY', 'hex')
// the destination address
const addressTo = '0x1463500476a3ADDa33ef1dF530063fE126203186'
// construct the transaction data
// NOTE: property 'nonce' must be merged in from web3.eth.getTransactionCount
// before the transaction data is passed to new Tx(); see sendRawTransaction below.
const txData = {
gasLimit: web3.utils.toHex(25000),
gasPrice: web3.utils.toHex(10e9), // 10 Gwei
to: addressTo,
from: addressFrom,
value: web3.utils.toHex(web3.utils.toWei('123', 'wei')) // Thanks @abel30567
// if you want to send just raw data (e.g. contract execution) rather than sending tokens,
// use 'data' instead of 'value' (thanks @AlecZadikian9001)
}
/** Signs the given transaction data and sends it. Abstracts some of the details of
* buffering and serializing the transaction for web3.
* @returns A promise of an object that emits events: transactionHash, receipt, confirmaton, error
*/
function sendRawTransaction(txData) =>
// get the number of transactions sent so far so we can create a fresh nonce
web3.eth.getTransactionCount(addressFrom).then(txCount => {
const newNonce = web3.utils.toHex(txCount)
const transaction = new Tx({ ...txData, nonce: newNonce }, { chain: 'mainnet' }) // or 'rinkeby'
transaction.sign(privateKey)
const serializedTx = transaction.serialize().toString('hex')
return web3.eth.sendSignedTransaction('0x' + serializedTx)
})
// fire away!
// (thanks @AndreiD)
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)
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment