2
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.

5

The error is quite clear, so I assume your question is about why the gas cost is 21004 instead of what you expected (21000).

The extra 4 gas is because you're sending a data field with one byte in it, and that byte is zero. Each zero you send costs 4 gas.

Just remove the data field and you should see the gas cost be 21000.

  • Is a byte of data always 4 gas? Or is it dependent on other variables? If my gas limit is 42,000 for example would it be 8 per byte? Assuming the 4 is constant, is it proper to start with a gas limit of 21k and then for each byte of data increase the gasLimit by 4 and decrease the amount/value sending by 4 WEI? – Albert Renshaw Dec 12 '18 at 17:01
  • @AlbertRenshaw Please ask a new question rather than commenting here. – smarx Dec 12 '18 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.