Created
March 28, 2018 16:29
-
-
Save x3388638/0eeeea50c0503e13e3c6a4f0d178704d to your computer and use it in GitHub Desktop.
Send ether via web3.js (ethereum, ETH)
This file contains 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 Tx = require('ethereumjs-tx'); | |
const Web3 = require('web3'); | |
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/')); | |
sendEther( | |
'SENDER_ADDRESS', | |
'SENDER_PRIVATE_KEY', | |
'RECEIVER_ADDRESS', | |
'AMOUNT_OF_ETHER' // 'all' for entire wallet | |
); | |
function sendRaw(rawTx, key) { | |
const privateKey = new Buffer(key, 'hex'); | |
const tx = new Tx(rawTx); | |
tx.sign(privateKey); | |
const serializedTx = tx.serialize(); | |
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function (err, txHash) { | |
if (err) { | |
console.error('sendRawTransaction failed.'); | |
console.error(err); | |
return; | |
} | |
console.log(txHash); | |
setTimeout(() => { | |
const transaction = web3.eth.getTransaction(txHash); | |
console.log(transaction); | |
}, 5 * 60 * 1000); | |
}); | |
}; | |
function sendEther(sender, key, receiver, etherValue) { | |
const rawTx = { | |
nonce: web3.toHex(web3.eth.getTransactionCount(sender)), | |
gasLimit: web3.toHex(21000), | |
gasPrice: web3.toHex(web3.eth.gasPrice), | |
to: receiver, | |
value: 0, | |
from: sender, | |
chainId: 1 | |
}; | |
if (etherValue.toString().toUpperCase() === 'ALL') { | |
const gasPrice = web3.eth.gasPrice.toString(10); | |
const gasVlaue = 21000 * gasPrice; | |
const totalBalance = web3.eth.getBalance(sender).toNumber(); | |
rawTx.value = web3.toHex(totalBalance - gasVlaue); | |
} else { | |
rawTx.value = web3.toHex(web3.toWei(etherValue, 'ether')); | |
} | |
sendRaw(rawTx, key); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment