How to Cancel a Transaction on Ethereum (2024)

Once your transaction gets confirmed on the Ethereum network, you cannot cancel it. However, you can effectively cancel transactions still in the Mempool by creating a second transaction with the same nonce (number only used once) but a higher gas fee. Since miners are incentivized to include the second transaction (with the higher gas fee) first, the nonce will be "used," and the original transaction will be dropped from the mempool.

Here are some possible reasons you might cancel a transaction:

  • You sent a transaction with a meager gas fee that is now stuck in a pending state.
  • You already know the transaction is going to fail.
  • You want to create a failsafe if something goes wrong with your transaction.

Metamask has a built-in feature that allows you to cancel pending transactions with one click.

How to Cancel a Transaction on Ethereum (1)How to Cancel a Transaction on Ethereum (2)How to Cancel a Transaction on Ethereum (3)

👍

Tip:

Set the max priority gas fee higher than your original transaction to ensure cancellation.

In this section, we will create our own cancellation transaction using Alchemy's SDK. (Web3.js code examples are also included.)

Prerequisites

Before you begin this tutorial, please ensure you have the following:

  • An Alchemy account (Create a free Alchemy account).
  • An Ethereum address or MetaMask wallet (Create a MetaMask wallet).
  • NodeJS and npm installed (Install NodeJs and NPM).

Connect to Alchemy

  1. From the Alchemy Dashboard, hover over Apps, then click +Create App.
  2. Name your app: Cancel-Tx.
  3. Select Ethereum as your chain and Sepolia as your network.
  4. Click Create app.

Request ETH from the Alchemy Sepolia faucet

  1. From Sepolia Faucet, sign in with your Alchemy account.
  2. Paste your MetaMask address and click Send me ETH.

🚧

Choosing a testnet

While you can use the Goerli testnet, we caution against it as the Ethereum Foundation has announced that Goerli will soon be deprecated.

We therefore recommend using Sepolia as Alchemy has full Sepolia support and a free Sepolia faucet also.

Open VS Code (or your preferred IDE) and enter the following in the terminal:

mkdir cancel-txcd cancel-tx

Once inside our project directory, initialize npm (node package manager) with the following command:

npm init

Press enter and answer the project prompt as follows:

package name: (cancel-tx)version: (1.0.0)description: entry point: (index.js)test command: git repository: keywords: author: license: (ISC)

Press enter again to complete the prompt. If successful, a package.json file will have been created in your directory.

Install environment tools

The tools you will need to complete this tutorial are:

  • Alchemy's SDK
  • dotenv (so that you can store your private key and API key safely)

To install the above tools, ensure you are still inside your root folder and type the following commands in your terminal:

Alchemy SDK:

npm install alchemy-sdk

Dotenv:

npm install dotenv --save

Create a Dotenv File

Create a .env file in your root folder. The file must be named .env or it will not be recognized.

In the .env file, we will store all of our sensitive information (i.e., our Alchemy API key and MetaMask private key).

Copy the following into your .env file:

API_KEY = "{YOUR_ALCHEMY_API_KEY}"PRIVATE_KEY = "{YOUR_PRIVATE_KEY}"
  • Replace {YOUR_ALCHEMY_API_KEY} with your Alchemy API key found in your app’s dashboard, under VIEW KEY:

How to Cancel a Transaction on Ethereum (4)

  • Replace {YOUR_PRIVATE_KEY}with your MetaMask private key.

To retrieve your MetaMask private key:

  1. Open the extension, click on the three dots menu, and choose Account Details.

How to Cancel a Transaction on Ethereum (5)

  1. Click Export Private Key and enter your MetaMask password.

How to Cancel a Transaction on Ethereum (6)

  1. Replace the Private Key in your .env file with your MetaMask Private Key.

Create cancelTx.js file

Create a file named cancelTx.js and add the following code:

const cancelTx = async () => { require("dotenv").config(); // Imports the secret .env file where our Private Key and API are stored // We can now use these aliases instead of using our actual keys. const { API_KEY, PRIVATE_KEY } = process.env; // Import the Alchemy SDK const { Network, Alchemy, Wallet } = require("alchemy-sdk"); // Initializes Alchemy SDK with our settings config const settings = { apiKey: API_KEY, network: Network.ETH_SEPOLIA, }; const alchemy = new Alchemy(settings); // The Wallet holds the private key and signs transactions for you. const walletInst = new Wallet(PRIVATE_KEY); // Gets the latest nonce for our wallet address const nonce = await alchemy.core.getTransactionCount(walletInst.address);};cancelTx();
const cancelTx = async () => { require("dotenv").config(); const { API_URL, PRIVATE_KEY } = process.env; const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); const web3 = createAlchemyWeb3(API_URL); const myAddress = "0x5DAAC14781a5C4AF2B0673467364Cba46Da935dB"; //TODO: replace this address with your own public address const nonce = await web3.eth.getTransactionCount(myAddress, "latest"); };cancelTx();

The code above sets up our Alchemy SDK to connect to the blockchain and send transactions.

Next, let's create two transactions. The first will be the transaction we intend to cancel and the second will be our cancellation transaction. See the code below, noting specifically lines 17-29:

const cancelTx = async () => { require("dotenv").config(); const { API_KEY, PRIVATE_KEY } = process.env; const { Network, Alchemy, Wallet, Utils } = require("alchemy-sdk"); const settings = { apiKey: API_KEY, network: Network.ETH_SEPOLIA, }; const alchemy = new Alchemy(settings); const walletInst = new Wallet(PRIVATE_KEY); const nonce = await alchemy.core.getTransactionCount(walletInst.address); const transaction = { gasLimit: "53000", maxPriorityFeePerGas: Utils.parseUnits("1", "gwei"), nonce: nonce, type: 2, chainId: 5, }; const replacementTx = { gasLimit: "53000", maxPriorityFeePerGas: Utils.parseUnits("1.55", "gwei"), maxFeePerGas: Utils.parseUnits("1.8", "gwei"), nonce: nonce, type: 2, chainId: 5, };};cancelTx();
const cancelTx = async () => { require("dotenv").config(); const { API_URL, PRIVATE_KEY } = process.env; const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); const web3 = createAlchemyWeb3(API_URL); const myAddress = "0x5DAAC14781a5C4AF2B0673467364Cba46Da935dB"; const nonce = await web3.eth.getTransactionCount(myAddress, "latest"); const transaction = { gas: '53000', maxPriorityFeePerGas: '1000000108', nonce: nonce, }; const replacementTx = { gas: '53000', maxPriorityFeePerGas: '1500000108', nonce: nonce, }; };cancelTx();

📘

Same nonce

Notice that we set the same nonce for both transactions.

Here's an overview of the transaction parameters:

  • gasLimit: The maximum amount of gas used to execute our transaction. 21000 wei is the minimum amount of gas an operation on Ethereum will use, so to ensure our transaction will be executed we put 53000 wei here.
  • maxPriorityFeePerGas: The miner's tip. (Check out Alchemy's guide to learn more)
  • maxFeePerGas: Transaction base fee + miner's tip
  • nonce: (number only used once) used to keep track of transactions for a specific address.
  • type: The EIP-2718 type of the transaction envelope.

Finally, let's send our transactions! For this, add the following try-catch statement, noting specifically lines 31-49:

const cancelTx = async () => { require("dotenv").config(); const { API_KEY, PRIVATE_KEY } = process.env; const { Network, Alchemy, Wallet, Utils } = require("alchemy-sdk"); const settings = { apiKey: API_KEY, network: Network.ETH_SEPOLIA, }; const alchemy = new Alchemy(settings); const walletInst = new Wallet(PRIVATE_KEY); const nonce = await alchemy.core.getTransactionCount(walletInst.address); const transaction = { gasLimit: "53000", maxPriorityFeePerGas: Utils.parseUnits("1", "gwei"), nonce: nonce, type: 2, chainId: 5, }; const replacementTx = { gasLimit: "53000", maxPriorityFeePerGas: Utils.parseUnits("1.55", "gwei"), maxFeePerGas: Utils.parseUnits("1.8", "gwei"), nonce: nonce, type: 2, chainId: 5, }; try { const signedTx = await walletInst.signTransaction(transaction); const signedReplacementTx = await walletInst.signTransaction(replacementTx); const txResult = await alchemy.core.sendTransaction(signedTx); const replacementTxResult = await alchemy.core.sendTransaction( replacementTx ); console.log( "The hash of the transaction we are going to cancel is:", txResult.hash ); console.log( "The hash of your replacement transaction is:", replacementTxResult.hash, "\n Check Alchemy's Mempool to view the status of your transactions!" ); } catch (error) { console.log( "Something went wrong while submitting your transactions:", error ); }};cancelTx();
const cancelTx = async () => { require("dotenv").config(); const { API_URL, PRIVATE_KEY } = process.env; const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); const web3 = createAlchemyWeb3(API_URL); const myAddress = "0x5DAAC14781a5C4AF2B0673467364Cba46Da935dB"; const nonce = await web3.eth.getTransactionCount(myAddress, "latest"); const transaction = { gas: '53000', maxPriorityFeePerGas: '1000000108', nonce: nonce, }; const replacementTx = { gas: '53000', maxPriorityFeePerGas: '1500000108', nonce: nonce, }; const signedTx = await web3.eth.accounts.signTransaction(transaction, PRIVATE_KEY); const signedReplacementTx = await web3.eth.accounts.signTransaction(replacementTx, PRIVATE_KEY); web3.eth.sendSignedTransaction(signedTx.rawTransaction, function (error, hash) { if (!error) { console.log( "The hash of the transaction we are going to cancel is: ", hash ); } else { console.log( "Something went wrong while submitting your transaction:", error ); } }); web3.eth.sendSignedTransaction(signedReplacementTx.rawTransaction, function (error, hash) { if (!error) { console.log( "The hash of your replacement transaction is: ", hash, "\n Check Alchemy's Mempool to view the status of your transactions!" ); } else { console.log( "Something went wrong while submitting your replacement transaction:", error ); } }).once("sent", () => { let timeout = new Promise(() => { let id = setTimeout(() => { clearTimeout(id); process.exit() }, 3000); }); return timeout; }); };cancelTx();

Above, we call the sendTransaction function and pass in our transaction.

To run our script, type this command in terminal:

node cancelTx.js

If successful, you should see an output similar to the following:

The hash of the transaction we are going to cancel is: 0x48b35baed265c5c7b31a16cf527a66f622923ad6cbe02c77a4af6438d528c199The hash of your replacement transaction is: 0x1145ea775a7889cdbdf1a29d41decd681adb9894b2351a324bf82923dfbd8b09 Check Alchemy's Mempool to view the status of your transactions!

On Alchemy, head to your app's dashboard and navigate to the Mempool tab.

After your replacement transaction has been mined, you should see that your first transaction was dropped and replaced:

How to Cancel a Transaction on Ethereum (7)

Nice work! You successfully created then canceled a transaction using Alchemy's SDK!

Feel free to reach out to us in the Alchemy Discord for help or chat with us @AlchemyPlatform on Twitter!

Updated about 1 year ago

How to Cancel a Transaction on Ethereum (2024)

FAQs

Can you cancel an Ethereum transaction? ›

Important information. Please note that once a transaction has been confirmed on the Ethereum blockchain, it is final and can no longer be sped up, reverted, or canceled. To speed up a pending or stuck transaction, you need to have enough ETH coins in your Ethereum account to cover the network fees.

Can I reverse an ETH transaction? ›

When a transaction is added to the blockchain, it undergoes confirmation by network participants, or miners, who validate and secure the transaction data. Once confirmed, the transaction is permanently recorded on the blockchain, making any alteration or reversal impossible.

How do you cancel a pending transaction? ›

Ask the merchant or retailer to reverse the charge, cancel the sale or release the hold for the confirmed amount. The sooner you can reach out to the merchant, the more likely the pending transaction can be canceled. If you suspect fraud, skip the merchant and call your bank or card issuer first.

How do I cancel a crypto transaction? ›

The reason you cannot cancel a cryptocurrency transaction is due to the nature of blockchain technology. The blockchain is a decentralised and distributed ledger that records all the transactions made on the network. Once a transaction is recorded on the blockchain, it cannot be altered or deleted.

Can I get my money back from Ethereum? ›

Funds sent wrongly to exchanges may be recovered at the exchange's discretion. Exchanges may be able to help you if you open a support ticket and give them the details they need,i.e., the address you meant to send to, and the transaction hash that went to the wrong address.

How to cancel a pending Ethereum transaction with MetaMask? ›

Open MetaMask extension. You should see the pending transaction if you accessed the same Ledger ETH account from Ledger Live. Click on the Cancel button. Check the details: the gas price, gas limit, and priority fee.

Can you get your ETH back? ›

Reclaiming lost Ethereum (ETH) is usually impossible. If sent to the wrong address, lost due to a forgotten private key, or stolen, it's generally irretrievable. Always double-check addresses and securely store private keys.

Can I get my ETH back from scammer? ›

Typically, when you report a crypto scam, the government will track down the criminals and get your funds back for you.

Is it possible to reverse a crypto transaction? ›

Can Bitcoin and other cryptocurrency transactions be reversed or cancelled? No, Bitcoin and other cryptocurrency transactions are designed to be irreversible.

How do I stop an online payment transaction? ›

To stop payment, you need to notify your bank at least three business days before the transaction is scheduled to be made and your bank may charge a fee. The notice to stop the transaction may be made orally or in writing. A bank can require written confirmation of an oral stop payment request.

How do you resolve a pending transaction? ›

Instead, it's best to contact the merchant directly and ask them to help resolve any issues with a pending credit or debit charge. A merchant might be able to remove a pending transaction before it posts to your balance.

Can a pending transaction be declined? ›

A pending credit card purchase might be declined if another merchant has placed a hold on your credit card. A pending purchase made with your bank account or credit card could be declined if your account doesn't have enough funds or the merchant won't accept payment from your bank.

Can pending crypto transactions be Cancelled? ›

Due to the nature of digital currency protocols, transactions cannot be cancelled or altered once they are initiated.

Can a successful transaction be reversed? ›

If either a consumer or a vendor notices something is wrong with the payment, they can contact the bank to stop the transaction going through. This is typically the payment reversal type which involves the least hassle for both customers and businesses.

How to check Ethereum pending transaction? ›

Understanding whether your transaction is pending is essential to managing your Ethereum dealings efficiently.
  1. Nonce Number Priority. ...
  2. Monitor Gas Fees. ...
  3. Visit Etherscan and Search Transaction Hash: ...
  4. Check the Transaction Status: ...
  5. Check Your Transaction on Etherscan: ...
  6. Access Your Wallet's RBF Feature:
Jan 11, 2024

Can you get your ETH back if you get scammed? ›

Typically, when you report a crypto scam, the government will track down the criminals and get your funds back for you. Hence, don't hesitate to work with your government.

Can Ethereum be withdrawn? ›

How to cash out Ethereum on Coinbase Wallet. Open your Coinbase wallet and select Ethereum. Choose the “Sell” option and enter the amount of ETH you wish to convert. Follow the prompts to sell your ETH for fiat currency, then withdraw the fiat to your linked bank account.

How do you revoke Ethereum? ›

Was this article helpful?
  1. Step 1: Use revoke access tools.
  2. Step 2: Connect your wallet.
  3. Step 3: Select a smart contract you wish to revoke.
  4. Step 4: Revoke access to your funds.
  5. Frequently asked questions. Does revoking token access also terminate staking, pooling, lending etc?

Top Articles
10 top Proof of Stake tokens in 2024
2024 IRS Tax Refund Schedule: When to Expect a Tax Refund
Red wine, berries, dark chocolate and tea: A recipe to reduce dementia risk
Bofa Financial Center Near Me
Mujeres Prepago Puerto Rico
Legend Piece Trello
Giant Eagle Hr Conn
One Fine Chocolate Place
Craigslist Personals Kenosha Wi
Jeff Bezos Lpsg
Virginia Family Resort (Kallithea): Alle Infos zum Hotel
Cvs Pcr Appointment
Medici Vermittlung GmbH sucht Facharzt (m/w/d) | Gynäkologie und Geburtshilfe (8662) in Cottbus | LinkedIn
Bhediya Full Movie Download
037Hdx
Wausau Marketplace
Thekat103.7
Rose Tree Park Italian Festival 2023
Top Songs On Octane 2022
Power Outage Map Albany Ny
Craigslist Rutland Vt Apartments
Salmon Fest 2023 Lineup
Workday Okta Nordstrom
Froedtert Billing Phone Number
Projectxyz Employee Portal
Steve Hytner Net Worth
Skip The Games Anchorage
New Jersey Cash Pop
Honeywell V8043E1012 Wiring Diagram
Forexfactory Calendar Today
Polyhaven Hdri
Equipment Hypixel Skyblock
Craigslist Ludington Michigan
Angels Pet World Hudson Wi
Madden 24 Repack
Registered Nurse Outpatient Case Manager Healthcare WellMed San Antonio Texas in San Antonio, TX for Optum
Serabii Net
Buying Pool Routes: Advice, Mistakes and Lessons Learned
Lady Eloise Cordelia Gordon-Lennox
Denverpost.com Login
Best Half Court Trap Defense
Bushnell Wingman Solid Orange Light
Funeral Questions and Answers
Tamil Dubbed Movie Download Kuttymovies
2021 Silverado 1500 Lug Nut Torque
A Place Next To Heaven: Fatin Ida Besik Ba Lalehan, come nuovo usato, spedizione gratuita... • EUR 12,37
Facebook Levels Fyi
Weitere relevante internationale Abkommen und Vereinbarungen
Directions To Cvs Pharmacy
Avalynn_Daniels
Craigslist Greencastle
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 5944

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.