Moving to @ethereumjs/tx
npm package after ethereumjs-tx
has been marked as deprecated.
My from
address has sufficient Kovan
network balance, but the following code throwing Insufficient funds
error.
Unable to figure out solution from github issue
const Web3 = require('web3')
import { Transaction } from '@ethereumjs/tx';
import Common, { Hardfork, Chain } from '@ethereumjs/common';
// Provider
var provider = 'https://kovan.infura.io/v3/xxxxxxxx';
var web3 = new Web3(new Web3.providers.HttpProvider(provider))
const from = '0xf169ae25afdb8cea6dc2de8938738234bafcaeb8'
const pKey = Buffer.from('e7abf3413731cea1963b845baede4925d7f7310dcc427513fa5752ec11fd098d', 'hex')
const to = '0x3314bf4B1286F495B1fe8908F7d0f05D8818b168'
const valueInEther = 0.001
web3.eth.getTransactionCount(from, "pending").then((txnCount) => {
console.log('From address nonce:' + web3.utils.numberToHex(txnCount));
web3.eth.getBalance(from).then((balRes) => {
console.log('From address balance (eth):' + web3.utils.fromWei(balRes.toString(18)));
});
var txObject = {
nonce: web3.utils.toHex(txnCount),
gasPrice: web3.utils.toHex(1000),
gasLimit: web3.utils.toHex(21000),
to: to,
value: web3.utils.toHex(web3.utils.toWei(valueInEther.toString(), 'ether')),
chainId: web3.utils.toHex(42) // kovan
}
const common = new Common({ chain: Chain.Kovan, hardfork: Hardfork.Istanbul }); //, hardfork: 'petersburg'
let tx = new Transaction(txObject, { common });
const signedTx = tx.sign(pKey);
const serializedTx = signedTx.serialize();
var rawTxHex = '0x' + serializedTx.toString('hex');
console.log("Signed transaction hex: " + rawTxHex);
// boardcast signed tx
web3.eth.sendSignedTransaction(rawTxHex)
.on('transactionHash', (txHash) => { console.log('transaction hash: ', txHash); })
.on('receipt', receipt => { console.log('Receipt: ', receipt); })
.catch(error => { console.log('Error: ', error.message); });
console.log(" ******************** Send result: ******************** ");
});