ethereum Proper Transaction Signing nonce
https://ethereum.stackexchange.com/questions/12823/proper-transaction-signing
const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const config = require('./config');
const web3 = new Web3(new Web3.providers.HttpProvider(config.provider)); //link provided by Infura.io
web3.eth.defaultAccount = "0xc929c890f1398d5c1ecdf4f9ecec016906ac9f7f";
const getNonce = () => {
return new Promise((resolve, reject) => {
web3.eth.getTransactionCount(web3.eth.defaultAccount, (error, result) => {
if(error) reject(error);
resolve(web3.toHex(result));
})
})
}
const getGasPrice = () => {
return new Promise((resolve, reject) => {
web3.eth.getGasPrice((error, result) => {
if(error) reject(error);
resolve(web3.toHex(result.toNumber()));
})
})
}
const sendRawTransaction = (rawTx) => {
const privateKey = "190b820c2627f26fd1b973b72dcba78ff677ca4395c64a4a2d0f4ef8de36883c";
const tx = new Tx(rawTx);
const privateKeyBuffer = Buffer.from(privateKey, 'hex');
tx.sign(privateKeyBuffer);
const serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
console.log('Error:', err);
console.log('Hash:', hash);
});
}
Promise.all([getNonce(), getGasPrice()])
.then(values => {
const rawTx = {
to: '0x203D17B4a1725E001426b7Ab3193E6657b0dBcc6',
gasLimit: web3.toHex(1000000),
value: web3.toHex(web3.toWei('0.1', 'ether')),
nonce: values[0],
gasPrice: values[1]
};
console.log(rawTx);
return(rawTx);
})
.then(sendRawTransaction)
.catch(e => console.log(e))