Skip to content

Instantly share code, notes, and snippets.

@MicrowaveDev
Created August 25, 2018 20:40
Show Gist options
  • Save MicrowaveDev/37667e24452cbd72428bbe2a826f0cc5 to your computer and use it in GitHub Desktop.
Save MicrowaveDev/37667e24452cbd72428bbe2a826f0cc5 to your computer and use it in GitHub Desktop.
// Its your address with some Ethereum balance
const fromAddress = '0x062c6ebe692d0E31B79Eff9532F835bF0dbc1f45';
// Its private key of your address
const privateKey = '0x3a622a1c7504b6be1b77a6b12ac1438d50ada2906bd871b15aefd627aec872aa';
// Its your friend's wallet address
const toAddress = '0x6122a161c39907502B8BB4636215374389B95c6f';
// Its amount of eth, which you want to send to friend
const ethAmount = 0.01;
// Convert it to wei https://etherconverter.online/
const weiAmount = ethAmount * (10 ** 18);
// Ethereum node, where do you send the transaction
const rpcServer = 'http://127.0.0.1:8545';
const Web3 = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider(rpcServer));
// First need to know gasPrice of the current network
web3.eth.getGasPrice().then(async (gasPrice) {
gasPrice = parseInt(gasPrice) || '1000000000';
// Second - get nonce of address(number of new transaction)
const txCount = await web3.eth.getTransactionCount(fromAddress);
let nonce = `${txCount++}`;
// Convert nonce, ethAmount, gasPrice and gasLimit to hex
const nonceHex = web3.utils.numberToHex(nonce);
const weiAmountHex = web3.utils.toHex(weiAmount);
const gasPriceHex = web3.utils.toHex(gasPrice);
const gasLimitHex = web3.utils.toHex("3000000");
var transactionOptions = {
nonce: nonceHex,
gasPrice: gasPriceHex,
gasLimit: gasLimitHex,
from: fromAddress,
to: toAddress,
value: weiAmountHex
};
// Create Transaction instance
var tx = new Tx(transactionOptions);
tx.sign(Buffer.from(config.private_key, 'hex'));
var stx = tx.serialize();
// Send transaction to rpc server
web3.eth.sendSignedTransaction('0x' + stx.toString('hex'), (err, hash) => {
if (err) { console.log(err); return; }
console.log('sent tx: ' + hash);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment