Created
January 18, 2019 04:50
-
-
Save bachdgvn/6d0ba093b0b93a1cd7a2f83229092149 to your computer and use it in GitHub Desktop.
Nodejs: How to broadcast raw transaction offline?
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
const Web3 = require('web3') | |
const Tx = require('ethereumjs-tx') | |
// connect to Infura node | |
const web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/3ee6d9d1b4454acea9e493bb66ed8e1c')) | |
// the address that will send the test transaction | |
const addressFrom = '0xFeBC5F91863Fc1a253362ddaD46537170Fdc61e5' | |
const privKey = 'xxxxxxxxxxxxxxxxxxx_METAMASKxxxxxxxxxxxxxxxxxxxx' | |
// the destination address | |
const addressTo = '0xcb238c6526AB2EADb70b2454f48629Fd38C89365' | |
// Signs the given transaction data and sends it. Abstracts some of the details | |
// of buffering and serializing the transaction for web3. | |
function sendSigned(txData, cb) { | |
let privateKey = null; | |
try { | |
privateKey = new Buffer(privKey, 'hex') | |
} catch(e) { | |
console.log(e) | |
} | |
const transaction = new Tx(txData) | |
transaction.sign(privateKey) | |
const serializedTx = transaction.serialize().toString('hex') | |
console.log('serializedTx: ', '0x' + serializedTx); | |
//web3.eth.sendSignedTransaction('0x' + serializedTx, cb) | |
} | |
// get the number of transactions sent so far so we can create a fresh nonce | |
web3.eth.getTransactionCount(addressFrom).then(txCount => { | |
// construct the transaction data | |
let txData = {}; | |
try{ | |
txData = { | |
nonce: web3.utils.toHex(0), | |
gasLimit: web3.utils.toHex(30000), | |
gasPrice: web3.utils.toHex(10e9), // 10 Gwei | |
to: addressTo, | |
from: addressFrom, | |
value: web3.utils.toHex(web3.utils.toWei('10000000', 'wei')) | |
} | |
} catch(e) { | |
console.log('e: ', e) | |
} | |
// fire away! | |
sendSigned(txData, function(err, result) { | |
if (err) return console.log('error', err) | |
console.log('sent', result) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment