[SOLVED] How can I set up a proper gas price for signTransaction?

Anyone knows how to set up a proper gas price for signTransaction on Polygon network?

I put a token sending feature into Moralis Cloud Function.
But sometimes it returns error: transaction underpriced because of the gas price.

May I know how much is the perfect gas and gasPrice here for Polygon?

  const tx = {
    from: sender_address,
    to: contract_address,
    gas: 100000,
    gasPrice: '5000000000',
    data: contract.methods.bulksendToken(receiver_addresses, amounts).encodeABI()
  }
  let result
  const signResp = await web3.eth.accounts.signTransaction(tx, p_key).then(async (signedTx) => {

I can check the current gas price from curl. But I still do not understand which number and how to put it into Cloud Function.

$ curl https://gasstation-mainnet.matic.network/v2
{
   "safeLow":{
      "maxPriorityFee":30.186666663866664,
      "maxFee":30.186666678866665
   },
   "standard":{
      "maxPriorityFee":31.41988763966667,
      "maxFee":31.41988765466667
   },
   "fast":{
      "maxPriorityFee":37.46498296513333,
      "maxFee":37.46498298013333
   },
   "estimatedBaseFee":1.5e-8,
   "blockTime":3,
   "blockNumber":33507368
}

The numbers in that api are gas prices in gwei, so you can set the gasPrice accordingly to that.

And for the gas(limit) parameter, you can estimate how much gas that transaction will take like this

let gasAmount = await contract.methods.bulksendToken(receiver_addresses, amounts).estimateGas({ from: sender_address });

and then maybe add a bit to this so you know it goes through

1 Like

It works!!!

Thank you!!

2 Likes

I thought it works. But it works around only 10%.
90% of my try failed with error: transaction underpriced

Do you know how to prevent transaction underpriced ?

My current code is like this.

  const gas = await contract.methods.bulksendToken(receiver_addresses, amounts).estimateGas({ from: sender_address });
  const gasPrice = web3.utils.toWei(request.params.gasPrice, 'gwei');

  const tx = {
    from: sender_address,
    to: contract_address,
    gas: gas,
    gasPrice: gasPrice,
    data: contract.methods.bulksendToken(receiver_addresses, amounts).encodeABI()
  }
  let result
  const signResp = await web3.eth.accounts.signTransaction(tx, p_key).then(async (signedTx) => {

request.params.gasPrice is the number from api callโ€™s โ€œfastโ€ โ€œmaxFeeโ€.

$ curl https://gasstation-mainnet.matic.network/v2

you could add 2-3 gwei to that result

To which one?

gas or gasPrice?

to gasPrice, that one is in gwei

Yes! Adding 3 gwei works perfectly. Thanks!!!

1 Like