0

I am sending a transaction with sendSignedTransaction :

const tx = new Tx({ ... "gasPrice": web3.utils.toHex(41 * 1e9), ... } await web3.eth.sendSignedTransaction(serializedTx) .on('transactionHash', (hash) => { console.log('waiting....'); }) .on('receipt', (receipt) => { console.log('... Transaction validated !'); }); 

It works fine. Here is what i want to do:

  • I want to set a very low value for gasPrice: For example 41 gwei
  • If the transaction is not validated after 15 seconds, i want to increase gasPrice to 51 gwei
  • etc.

How can I do that programmatically ?

Thanks

1 Answer 1

0

You can send the same transaction but with a different tx['gasPrice'], if the new transaction has the same tx['nonce'] then the transacition with an higher gas price will be added to the next block by the miners and so the old one will be automatically discarded .

However 15 seconds is a very small time interval, maybe it's better to resend the transaction at every new block (currently the average block time is about 13 seconds) setting the gas price to a percentage of the previous block gas price and trying to increment this percentage at every new block.

5
  • Thanks a lot. 15 second was an example. I know this is possible to send the same transaction with same nonce but i want to know if there is a best way to do that ? Because it will cost gas... Commented May 26, 2021 at 7:38
  • The gas is consumed only if the transaction gets added to a block, the gas you'll spend is the gas used by the transaction with the higher gas price. Commented May 26, 2021 at 12:11
  • Thanks but why should we pay gas for canceling a pending transaction in metamask ? Commented May 26, 2021 at 20:51
  • Cancelling a pending transaction means submitting an empty transaction with a value of 0 Ether (it costs 21000 gas) and the same nonce but an higher gas price, miners simply ignore the transaction with a lower gas price. Replacing a transaction is the same but the new transacion is not empty. Commented May 27, 2021 at 12:15
  • @AndreaCiceri sounds good. Could you update you answer with code example using web3js which will cancel or replace pending tx. Commented Oct 12, 2021 at 9:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.