-
-
Save raineorshine/c8b30db96d7532e15f85fcfe72ac719c to your computer and use it in GitHub Desktop.
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 raw data (e.g. contract execution) rather than sending tokens, | |
// use 'data' instead of 'value' (thanks @AlecZadikian9001) | |
// e.g. myContract.methods.myMethod(123).encodeABI() (thanks @NguyenHoangSon96) | |
} | |
/** 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 | |
*/ | |
const 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) | |
}) | |
) |
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!
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?
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.
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?
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
@Aldekein Thanks! Updated. What version of web3
are you using btw?
Would it be possible to see an example with a contract deployment as the transaction? Thanks!
updated version of this script. https://gist.github.com/AndreiD/675027abdaa885716ce2c5af16166510
Updated from @AndreiD's script. If someone could confirm that the updated gist works for them, that would be great.
Thank you @AlecZadikian9001 for the tip. Updated with comment.
Thanks @abel30567. Updated.
Hello, i get an error sendRawTransaction(txData).then(result =>
^
TypeError: Cannot read property 'then' of undefined
@EffMining What version of web3 are you on?
Encountered the same error as @EffMining, use web3 v1.2.2, ethereumjs-tx v2.1.1.
Also got error
function sendRawTransaction(txData) =>
^^
SyntaxError: Unexpected token =>```
@simplespy Sorry, that should be: const sendRawTransaction = txData =>
I am getting such an unhelpful error:
Error: Returned error: VM Exception while processing transaction: revert
It is driving me crazy. Does anyone have any ideas why this could be failing?
transactionData = myContract.methods.foo('bar');
gasPrice = await web3.eth.getGasPrice();
account = web3.eth.accounts.privateKeyToAccount(privateKey);
txCount = await web3.eth.getTransactionCount(account.address, 'pending');
rawTx = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex('800000'),
gasPrice: web3.utils.toHex(gasPrice),
to: smartContractAddressTreasury,
value: fee,
data: transactionData,
};
@acidic9 It's probably an error in smartContractAddressTreasury
. Either it is a bug, or you may be passing the wrong data or in the wrong format.
@acidic9 I think you forget to encode the data like so transactionData.encodeABI()
Thanks guys. I think the issue was just that my gas limit was too low :/
I get the following error when trying to send a transaction over the kovan test network
error Error: Returned error: Invalid chain id.
at Object.ErrorResponse (/Users/laurenswissels/node_modules/web3-core-helpers/lib/errors.js:28:19)
at /Users/laurenswissels/node_modules/web3-core-requestmanager/lib/index.js:288:36
at XMLHttpRequest.request.onreadystatechange (/Users/laurenswissels/node_modules/web3-providers-http/lib/index.js:98:13)
at XMLHttpRequestEventTarget.dispatchEvent (/Users/laurenswissels/node_modules/xhr2-cookies/xml-http-request-event-target.ts:44:13)
at XMLHttpRequest._setReadyState (/Users/laurenswissels/node_modules/xhr2-cookies/xml-http-request.ts:219:8)
at XMLHttpRequest._onHttpResponseEnd (/Users/laurenswissels/node_modules/xhr2-cookies/xml-http-request.ts:345:8)
at IncomingMessage.<anonymous> (/Users/laurenswissels/node_modules/xhr2-cookies/xml-http-request.ts:311:39)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1220:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
data: null
}
Does HttpProvider still work in web3 1.0? I thought it was being deprecated.