web3 = new Web3(new Web3.providers.HttpProvider("https://kovan.infura.io/"));
router.post('/sendEth', (req, res) => {
var fromaddress = req.body._fromaddress;
var amount = req.body._amount;
var privatekey = req.body._privatekey;
var toAddress = req.body._toAddress;
// Step 1
var payloadData = web3.toHex(web3.toWei(amount, 'ether'));
var transactionObject = {
'from': fromaddress,
'to': toAddress,
'value': payloadData
}
gasLimit = web3.eth.estimateGas(transactionObject);
// Step 2
gasPrice = web3.eth.gasPrice;
totalGas = gasPrice * gasLimit;
var amountToSend = web3.toWei(amount, 'ether') - totalGas;
payloadData = web3.toHex(amountToSend);
gasPriceHex = web3.toHex(gasPrice);
gasLimitHex = web3.toHex(gasLimit);
nonce = web3.eth.getTransactionCount(fromaddress, "pending");
nonceHex = web3.toHex(nonce);
var rawTx = {
nonce: nonceHex,
gasPrice: gasPriceHex,
gasLimit: gasLimitHex,
to: toAddress,
from: fromaddress,
value: payloadData,
data: '0x00'
};
// Step 3
var key = Buffer.from(privatekey, 'hex');
var tx = new Tx(rawTx);
tx.sign(key);
var serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function (err, hash) {
if (err) {
res.status(401).json("" + err);
}
else {
res.json({"status": true, "hash": hash});
}
});
});
Above is my code in nodejs for sending entire balance in ether where I get error for gas price:
Error: Transaction gas is too low. There is not enough gas to cover minimal cost of the transaction (minimal: 21004, got: 21000). Try increasing supplied gas.
This is the correct method to send ether, but still get this error.