Cancel a Pending Transaction

How to create a new transaction with a desired nonce.

Sometimes Transactions Get Stuck

Transactions stuck in the EVM's memory queue are generally a result of paying a lower gas fee than the chain can accommodate. If a transaction sticks, all further transaction will not be executable.

To clear these pending transactions it is required to create a new transaction with the same nonce.

The "nonce" is the index of the transaction for that user on the blockchain. Example: If the user has made 10 transactions on the blockchain previously, the nonce of a new transaction will be 11.

ORE ID allows the developer to manually set the nonce value for a transaction. If a transaction is stuck pending, then that nonce must be used to create a new transaction (generally with zero value) with a higher gasPrice and gasLimit.

Checking for Pending Transactions

import Web3 from "web3"

const chainAccount = "0x01...01" // Ethereum Public Address
const goerliEndpoints = [
    { url: "https://rpc.ankr.com/eth_goerli" },
]

const provider = new Web3.providers.HttpProvider(
    goerliEndpoints[0].url
)
const web3 = new Web3( provider )

const highestNonceExecuted = await web3.eth.getTransactionCount(
    chainAccount,
    'latest'
)
console.log( 'last nonce executed: ', highestNonceExecuted )

const highestNoncePending = await web3.eth.getTransactionCount(
    chainAccount,
    'pending'
)
console.log( 'highest nonce pending: ', highestNoncePending )

If the highest nonce executed is equal to the highest nonce pending, the account has no pending transactions.

if ( highestNoncePending === highestNonceExecuted ) {
    console.log( 'No Pending Transactions' );
} 

If the highest nonce pending is greater than the highest nonce executed, then the account has pending transactions which may need cleared.

else if ( highestNoncePending > highesNonceExecuted ) {
    numPending = highestNoncePending - highestNonceExecuted
    console.log( '{numPending} Transaction/s Pending' );
}

The highest nonce pending is used as the nonce for the zero value transaction that will override the pending transaction. See the sample transaction below.

Sample Transaction Data

{
    "from": "0x01...01",
    "to": "0x01...01",
    "value": "0x00",
    "gasLimit": 145000,
    "nonce": highestNoncePending
}

Last updated