Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
})
)
@kn1g

This comment has been minimized.

Copy link

kn1g commented Jan 14, 2018

Hey, I also did it like this. It creates the tx

sent 0x8a7f177c094c5a41783862c314054ce632ed842c0ef379706febe9ff7d600df2

But I get the response:

Unhandled rejection Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!

Any experience with this error?

@sandstrom

This comment has been minimized.

Copy link

sandstrom commented Jan 18, 2018

Perhaps you need to put in more gas.

See this webpage for current gas levels: https://ethgasstation.info/

@zcrash

This comment has been minimized.

Copy link

zcrash commented Mar 5, 2018

I get this error every time I send a tx with web3. It doesn't matter what the gas price is set to. Because the transactions are still broadcast with out issue I've just ignored the error. Worth note, my configuration is different in that I my provider is a local GETH node and not Infura. Running web3@1.0.0-beta.18.

@otembajelle

This comment has been minimized.

Copy link

otembajelle commented Mar 21, 2018

I experienced the same and saw 1.0.0-beta.22: ethereum/web3.js#1102.

With me the tx was executed and showed ok at Etherscan.

@AlecZadikian9001

This comment has been minimized.

Copy link

AlecZadikian9001 commented Apr 9, 2018

If you want to send the raw data of a transaction (e.g. one involving a contract) rather than sending tokens, the txData dict should have "data" as the key instead of "value."

@jtakalai

This comment has been minimized.

Copy link

jtakalai commented Apr 12, 2018

Does HttpProvider still work in web3 1.0? I thought it was being deprecated.

@abel30567

This comment has been minimized.

Copy link

abel30567 commented May 28, 2018

This works great! I've been looking for something like this. You'll need to make the 123 wei number into a string however. Thanks!

@saitam1

This comment has been minimized.

Copy link

saitam1 commented Jul 9, 2018

Doing the same on Kovan and experiencing this error:

sent 0xb14852674c10adfdaf590c687d5502ea0d992d469791ae8e4094b22ccfc0de5d
(node:20982) UnhandledPromiseRejectionWarning: Error: Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
    at /home/user/code/node_modules/web3-core-method/src/index.js:392:42
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)
(node:20982) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20982) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Anybody found a solution?

@kikoncuo

This comment has been minimized.

Copy link

kikoncuo commented Oct 31, 2018

Same problem, sending a signed transaction using web3 1.0 to Kovan through Infura, I get the receipt so the node has accepted the transaction, but if this is happening to multiple users, seems like Infura is not broadcasting signed transactions in Kovan.
I can't see it in my other node, or in etherscan.

@anil215

This comment has been minimized.

Copy link

anil215 commented Nov 16, 2018

How to prevent replayProtection here.. i mean we can take the signed raw tx and broadcast in eth classic network provided the sending acc complies with the nonce and balance check?

@Aldekein

This comment has been minimized.

Copy link

Aldekein commented Aug 1, 2019

I've been gettinig an error UnhandledPromiseRejectionWarning: TypeError: Tx is not a constructor with the latest version of ethereumjs-tx package until I updated the line 2 to: const Tx = require('ethereumjs-tx').Transaction

@raineorshine

This comment has been minimized.

Copy link
Owner Author

raineorshine commented Aug 1, 2019

@Aldekein Thanks! Updated. What version of web3 are you using btw?

@mayeaux

This comment has been minimized.

Copy link

mayeaux commented Sep 4, 2019

Would it be possible to see an example with a contract deployment as the transaction? Thanks!

@AndreiD

This comment has been minimized.

Copy link

AndreiD commented Oct 31, 2019

@raineorshine

This comment has been minimized.

Copy link
Owner Author

raineorshine commented Nov 1, 2019

Updated from @AndreiD's script. If someone could confirm that the updated gist works for them, that would be great.

@raineorshine

This comment has been minimized.

Copy link
Owner Author

raineorshine commented Nov 1, 2019

Thank you @AlecZadikian9001 for the tip. Updated with comment.

@raineorshine

This comment has been minimized.

Copy link
Owner Author

raineorshine commented Nov 1, 2019

Thanks @abel30567. Updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.