I Try to use @ethereumjs/tx to sign Transaction. I want to send ETH from one address to second address.
....
const legacy = require( @ethereumjs/tx/dist/legacyTransaction );
const utils = require( web3-utils );
const {Personal} = require( web3-eth-personal );
....
// https://docs.chainstack.com/reference/ethereum-sendrawtransaction
const from = request.body.from;
const to = request.body.to;
const amount = 0.01 ;
const passphrase = request.body.passphrase;
const private_key = getPrivateKey(from, passphrase);
// Define the gas limit
const gasLimit = await new Web3Eth(local_provider).estimateGas({
from: from,
to: to,
});
// Get the transaction count for the sender address
const nonce = await new Web3Eth(local_provider).getTransactionCount(from);
// Define the transaction object
const txData = {
from,
nonce: nonce,
to,
gasLimit: 21000,
maxPriorityFeePerGas: utils.toHex(utils.toWei("5", "gwei")),
maxFeePerGas: utils.toHex(utils.toWei("20", "gwei")),
value: utils.toHex(utils.toWei( 0.01 , ether )),
};
const tx = legacy.Transaction.fromTxData(txData);
const signedTx = tx.sign(private_key);
const serializedTx = signedTx.serialize();
const rawTransaction = 0x + serializedTx.toString( hex );
try {
console.log(`Sending transaction...`);
const result = await new Web3Eth(provider).sendSignedTransaction(rawTransaction);
console.log(`Transaction hash: ${result.transactionHash}`);
} catch (error) {
console.error(error);
}
reason: err: insufficient funds for gas * price + value: address 0x2f1030396172F3e3d308819833fBbA655A9785a3 have 19175306697701238 want 16737889130546396655769049807908504612912 (supplied gas 21000) ,
when I change to:
var tet = utils.toWei( 0.01 , ether );
const txData = {
from,
nonce: nonce,
to,
gasPrice: "0x" + parseInt(18000000000, 10).toString(16),
gasLimit: "0x" + parseInt(90000, 10).toString(16),
value: "0x" + parseInt(tet, 10).toString(16),
};
It s works Perfect!
My wish is not to set the gas fees and prices. I wish to make it auto.
but without inject the gas, it will not work.