Skip to content

Instantly share code, notes, and snippets.

@TOMOAKI12345
Last active March 2, 2023 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TOMOAKI12345/1fb64207aaf939c840ab8664aabc0cd6 to your computer and use it in GitHub Desktop.
Save TOMOAKI12345/1fb64207aaf939c840ab8664aabc0cd6 to your computer and use it in GitHub Desktop.
cancel transaction on Ethereum blockchain
// 1. replace {eth_tx_id_you_want_to_cancel_here} with the transaction id you want to cancel
// 2. $ node cancelTransaction.js
// [notice] you need to run this code before your transaction included into blockchain.
// Depends on network status, you can not cancel. Use this code with your own reponsibility. And there's no guarantee if this works.
var Web3 = require("web3");
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var eth = web3.eth;
var jayson = require("jayson"); // need to install jayson. "$ npm install jayson"
var client = jayson.client.http({
host: "localhost",
port: 8545
});
var targetCancelTxId = "{eth_tx_id_you_want_to_cancel_here}";
cancelTransaction(targetCancelTxId)
function cancelTransaction(cancelTransactionId){
var transactionDetail = web3.eth.getTransaction(cancelTransactionId)
var cancelTxFrom = transactionDetail.from;
var cancelTxNonce = transactionDetail.nonce;
var cancelGasPrice = transactionDetail.gasPrice;
if(cancelTxFrom && cancelTxNonce && cancelGasPrice){
sendToMyselfWithSameNonce(cancelTxFrom, cancelTxNonce, cancelGasPrice)
}
}
function sendToMyselfWithSameNonce(cancelFromAddress, cancelNonce, cancelGasPrice){
var gas = 300000;
var gasPrice = cancelGasPrice * 10; // 10 times higher gasPrice than the transaction you want to cancel
var sendingWei = 0;
var params = [{
"from": cancelFromAddress,
"to": cancelFromAddress, // send to myself to cancel.
"gas": "0x" + gas.toString(16), //,
"gasPrice":"0x" + gasPrice.toString(16), //
"value": "0x" + sendingWei.toString(16), //
"nonce": "0x" + cancelNonce.toString(16),
"data": "" //
}]
console.log(params)
if(!cancelFromAddress){
return
}
client.request('eth_sendTransaction', params, function(err, response) {
if(err) {
console.log(err)
}
console.log(response); // 2
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment