You should send your transaction with safe gas price. Here is my code how I am getting gas price:
async function getCurrentGasPrices() {
let response = await axios.get('https://ethgasstation.info/json/ethgasAPI.json');
let prices = {
low: response.data.safeLow/10,
medium: response.data.average/10,
high: response.data.fast/10
};
return prices;
}
Following function will show price in ETH:
async function actualNetworkFee() {
return new Promise(async (resolve) => {
let gasPrices = await getCurrentGasPrices();
let low = parseFloat(((21000 * gasPrices.low) / 1e9).toFixed(8));
let medium = parseFloat(((21000 * gasPrices.medium) / 1e9).toFixed(8));
let high = parseFloat(((21000 * gasPrices.high) / 1e9).toFixed(8));
let fee = { low, medium, high };
console.log('Ether fee',fee)
resolve(fee)
})
}
You need to set price in following way when sending ETH:
async function transferEther(fromAddress, toAddress, amount, privateKey, nonceAdd, networkFeeType) {
return new Promise(async (resolve, reject) => {
try {
web3js.eth.getTransactionCount(fromAddress, async (err, txCount) => {
networkFeeType = networkFeeType.toLowerCase();
var nonce = web3js.utils.toHex(txCount + nonceAdd)
let gasPrices = await getCurrentGasPrices();
let value = web3js.utils.toHex(web3.utils.toWei(amount.toString(), 'ether'));
let gas = 21000;
let gasPrice =web3js.utils.toHex(gasPrices.low* 1e9);
if (networkFeeType == 'avg') {
gasPrice = web3js.utils.toHex(gasPrices.medium* 1e9);
}
else if (networkFeeType == 'max') {
gasPrice = web3js.utils.toHex(gasPrices.high* 1e9);
}
let details = {
"to": toAddress,
"value": value,
"gas": gas,
"gasPrice": gasPrice,
"nonce": nonce,
"chainId": parseInt(process.env.chainID) // EIP 155 chainId - mainnet: 1, rinkeby: 4
};
const transaction = new EthereumTx(details, { chain: process.env.chain });
privateKey = privateKey.split('0x');
let privKey = Buffer.from(privateKey[1], 'hex');
transaction.sign(privKey);
const serializedTransaction = transaction.serialize();
web3js.eth.sendSignedTransaction('0x' + serializedTransaction.toString('hex'), (err, id) => {
if (err) {
resolve({ success: false, err: err.toString() });
}
const url = config.get("ETHERSCAN_API") + `/tx/${id}`;
console.log(url);
resolve({ success: true, hash: id });
});
})
}
catch (err) { reject(err) }
});
}
Hopefully this code will help a lot of developers :)