Created
July 17, 2018 10:08
-
-
Save rajeshsubhankar/346e2788433f4ed2c9a74ae10dfbf667 to your computer and use it in GitHub Desktop.
In development mode while dealing with lot of transactions handling Metamask pop-ups are pain. To avoid that we can create and sign raw transactions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Web3 = require('web3'); | |
const Tx = require('ethereumjs-tx') | |
var web3 = new Web3(Web3.givenProvider || "ws://localhost:8546"); | |
// the address that will send the test transaction | |
const addressFrom = '0xDFf7787B927c0F03C3a8a49aF6726a074923663c' | |
//private key of above address | |
const privKey = 'replace_me' | |
//address to receive ether | |
const addressTo = '0x002E28950558Fbede1A9675Cb113F0BD20912019' | |
//Return number of transactions sent so far from the given address | |
function getTransactionCount(address) { | |
return new Promise(function(resolve, reject) { | |
web3.eth.getTransactionCount(address) | |
.then((txCount) => { | |
resolve(txCount) | |
}) | |
.catch((error) => { | |
reject(error) | |
}) | |
}) | |
} | |
//send raw transaction (sendSignedTransaction in web3.js v1.0.0) | |
function sendTransaction(txData) { | |
return new Promise(function(resolve, reject) { | |
const privateKeyHex = new Buffer(privKey, 'hex') | |
const transaction = new Tx(txData) | |
transaction.sign(privateKeyHex) | |
const serializedTx = transaction.serialize().toString('hex') | |
web3.eth.sendSignedTransaction('0x' + serializedTx) | |
.on('transactionHash', function(hash){ | |
console.log('transaction hash ', hash) | |
}) | |
.on('receipt', function(receipt){ | |
console.log('transaction receipt ', receipt) | |
}) | |
.on('confirmation', function(confirmationNumber, receipt){ | |
console.log('confirmationNumber ', confirmationNumber) | |
resolve(receipt) }) | |
.on('error', function(error) { | |
reject(error) | |
}); // If a out of gas error, the second parameter is the receipt. | |
}) | |
} | |
//create raw transaction data and fire | |
getTransactionCount(addressFrom) | |
.then((txCount => { | |
// construct the transaction data | |
const txData = { | |
nonce: web3.utils.toHex(txCount), | |
gasLimit: web3.utils.toHex(250000), | |
gasPrice: web3.utils.toHex(10e9), // 10 Gwei | |
to: addressTo, | |
from: addressFrom, | |
value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')) | |
} | |
sendTransaction(txData) | |
.then((response) => { | |
console.log('transaction sent ', response) | |
}) | |
.catch((error) => { | |
console.log('transaction failed ', error) | |
}) | |
})) | |
.catch((error) => { | |
console.log('transaction count failed ', error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment