Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined! #1102

Closed
vbaranov opened this issue Oct 9, 2017 · 58 comments · Fixed by #1414

Comments

@vbaranov
Copy link

vbaranov commented Oct 9, 2017

web3@1.0.0-beta.22
Contract deployment with MetaMask 3.10.9: https://etherscan.io/tx/0xccec451b8a66dc3a44318cd45924893715564e7758245031ef9700acbb21d127

Transaction mining duration was approximately 2 mins and only 3 - 5 blocks were generated before it was mined.
Why does web3 think, that it was 50 blocks and it catches an error here? is this a bug?

@pannous
Copy link

pannous commented Oct 19, 2017

yes, seams to be a horrible bug.
also you paid ($3.06) just tx cost!

@DSalko
Copy link

DSalko commented Oct 25, 2017

Can this be related to Infura? I see this a lot on testnet too.

@adonley
Copy link
Contributor

adonley commented Nov 2, 2017

I think I found the error. When I call a contract function and "await" the send, startWatching is invoked from the file web3-core-method/src/index.js . I didn't achieve a pub/sub so a 1 second interval is set. Every time this 1 second interval passes return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result)) is called and we don't have an existing receipt so getTransactionReceipt with a txhash which is valid. But it hasn't been included yet so if (!receipt || !receipt.blockHash) {throw new Error('Receipt missing or blockHash null');} is invoked and the catch at the bottom of the statement increments a timeout. After 50 tries, this error is achieved. This 50 tries is supposed to be reserved for 50 blocks.

Found this running a private chain testing some code. Let me know if I can provide additional info.

@wcw84
Copy link

wcw84 commented Nov 3, 2017

I have found the same problem in the main chain. Everything seems OK, but this errors just jump out. How to fix it?

@adonley
Copy link
Contributor

adonley commented Nov 3, 2017

I needed to quick fix so I commented out the code in the catch for now. If I have time I will try to pull request it but this one is interesting because two different timeout ideas are clashing.

From the directory where node_modules is located you can run: sed -i '/(timeoutCount - 1 >= TIMEOUTBLOCK)/,+4 d' node_modules/web3-core-method/src/index.js and it will delete out the timeout.

@Freydal
Copy link

Freydal commented Dec 11, 2017

Is there anything I can do to increase the likelihood of successful subscribe? I am seeing this issue across multiple projects intermittently.

@adonley
Copy link
Contributor

adonley commented Dec 12, 2017

I can take a look at it in the next few days and see about a pull request. I'm not actively using web3 on a project at the moment so it's going to take me a bit. If anyone else starts this lmk.

@utkarsh17ife
Copy link

Any updates on this?

@MaggieNgWu
Copy link

Same problem

@devdany
Copy link

devdany commented Jan 4, 2018

same problem.
Have you received a transaction with a transaction and received this error or a transaction without this error?
my transaction is not contained in mainnet.
in testrpc, no problem. but in mainnet, i get this error

@MaggieNgWu
Copy link

I turn to use "truffle-contract" module, it run smoothly now.

Original code use web3 to deploy contract get error "ransaction was not mined within 50 blocks":

var newDC = new web3.eth.Contract(DContract.abi);
	newDC.deploy({
		data:DContract.bytecode ,
		arguments: arg
	}).send({
		from: account,
		gas: 4000000,
		gasPrice: 30000000000000
	},function(error,transactionHash){
		console.log(error);
		console.log('Ethreum transaction', transactionHash, 'successfully posted.');
	}).then(function(newContractInstance){
		//const SC = new web3.eth.Contract(SContract.abi,config.ethereum.summary);
	    alert("Contract Address : "+newContractInstance.options.address); // instance with the new contract address
	});

Turn to use truffle-contract runs well, I don't know why.

var TruffleContract = require("truffle-contract");
var Web3 = require('web3');
var provider = new Web3.providers.HttpProvider(config.ethereum.ipcrpc);
const DCJSON = require('./../../contracts/DataContract.json'); 

var arg=[.....]
createDataContract(arg).then(function(instance){
	console.log(instance.address);
},function(err){
	console.log(err);
})

function createDataContract(arg){
	return new Promise(function(resolve,reject){
		var DContract = loadContract(DCJSON, provider, account);
		DContract.new(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],arg[7]).then(function(newDc){
			resolve(newDc);
		}).catch(function(err){
			reject(err);
		});
	})
	
}
function loadContract(contractjson, provider, address) {
	let contract = TruffleContract(contractjson);
    contract.setProvider(provider);
    if (typeof contract.currentProvider.sendAsync !== "function") {
		contract.currentProvider.sendAsync = function() {
			return contract.currentProvider.send.apply(
			  contract.currentProvider, arguments
			);
		};
	}
    contract.defaults({ from: address, gas: 4500000 });
    return contract;
}

@zaro
Copy link

zaro commented Jan 4, 2018

I can confirm the same issue when using version 1.0.0-beta.27 , metamask and the following code:

  const contract = new web3.eth.Contract(abi);
  const p = contract.deploy({
      data:bytecode,
      arguments: params,
  })
  .send({
      gas: gasEstimate,
      gasLimit: 4000000,
      from: fromAddress,
   })
  .catch(e=> {
    console.error('deployContract error', e);
    dispatch(deployError(contractName, e));
    throw e;
  })
  .then(function(newContractInstance){
    if(newContractInstance){
      console.log(`${contractName} Adress`, newContractInstance.options.address);
      dispatch(deployComplete(contractName, newContractInstance.options.address));
    }
    return newContractInstance;
  });

This fails on both rinkeby and my private chain, and the failures seem random, e.g. sometimes the contract is deployed and sometimes it fails with this error.

@strelok1
Copy link

Yep, this is extremely annoying especially in this time of network congestion while using Infura that is taking on average 5 mins to even broadcast the transaction. @adonley have you been able to patch it locally?

@Andromelus
Copy link

We have the same problem here on a private chain and a contract deployment with a signedTransaction and web3js. If any stable solution (not changing library code would be great :D ), please share :)

@Freydal
Copy link

Freydal commented Jan 12, 2018

It is my understanding that the then and confirmation PromiEvent are the components effected by this error.

This for example is an implementation that may be effected:

transaction.send(options).then((receipt) => { doSomething() });

This alternative should execute properly but is much more verbose:

let txHash;
transaction.send(options).once('transactionHash', hash => txHash = hash).then((receipt) => {
  doSomething()
}).catch((e) => {
  if(e.includes('not mined within 50 blocks')) {
    const handle = setInterval(() => {
      web3.eth.getTransactionReceipt(txHash).then((resp) => {
        if(resp != null && resp.blockNumber > 0) {
          clearInterval(handle);
          doSomething();
        }
      } 
    });
  }

@Andromelus
Copy link

Thank you for that. Will try it as soon as possible!

@kn1g
Copy link

kn1g commented Jan 14, 2018

Hi, get the same error ().

I use infura and set up a raw transaction and basically try to send it with:

const Web3      = require('web3');
const Tx        = require('ethereumjs-tx');
var web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/KEY"));
const txData = {
                    nonce:      web3.utils.toHex(txCount),
                    value:      '0x0', 
                    from:       addressFrom,
                    gas:        web3.utils.toHex(req.body.maxGas),
                    gasPrice:   web3.utils.toHex(req.body.gasP), 
                    to:         myContract._address,
                    data:       myContract.methods.transfer(req.body.AddressTo, TokenAmount).encodeABI(),  
                }
sendSigned(user.privKey, req, txData, function(err, result) {
                    if (err) return console.log('error', err);  
                    console.log('sent', result);
                });
function sendSigned(encPrivKey, req, txData, cb) {
    const privateKey  = new Buffer(privKey, 'hex');
    const transaction = new Tx(txData);
    transaction.sign(privateKey);
    const serializedTx = transaction.serialize().toString('hex');
    web3.eth.sendSignedTransaction('0x' + serializedTx, cb);
}

gives me the TxHash but

Unhandled rejection Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!

And transaction is not mined.

Edit.:
Turned out that the gas limit was way too low. But than this error is completely misleading :/

@Andromelus
Copy link

Andromelus commented Jan 15, 2018

@kn1g Can you say what was your gas limit? I'm a 4 millions for now, which seems way enough for that :S

@kn1g
Copy link

kn1g commented Jan 15, 2018

I raised the gas limit to 160000 for a simple transaction. It seemed to work - but the error is still annoying...
4 Million is really a lot. What is the block gas limit atm?

@Andromelus
Copy link

Blick limit is 4.7 millions. With more investigation, it seems like my transaction is not correct, I cannot estimate the gas cost of it.

@kn1g
Copy link

kn1g commented Jan 15, 2018

I also had trouble estimating it. It actually seems to work for plain transactions. But if you estimate it for a contract call it may take a LONG time or just times out.

I'm using infura.io. In the end I just removed the estimate gas function and replaced it with hardcoded default values for different scenarios... :/

@stefanbinder
Copy link

Same here, I'm able to deploy my Greeter Tutorial contract but not more.

With other contract for a real token, I get different errors like that mentioned.
As well:
Unhandled rejection Error: Returned error: exceeds block gas limit
Unhandled rejection Error: The contract code couldn't be stored, please check your gas limit.
Unhandled rejection Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!

Not sure whats the cause.
The build-script with web3 for the greeter and token-contract is the same, so I guess its the contract itself?

bshevchenko added a commit to bshevchenko/web3-core-method that referenced this issue Feb 13, 2018
@woniesong92
Copy link

Same here

@onairelav
Copy link

idem

just to see the receipt it's possible to comment the code inside the catch that raise the error

t/node_modules/web3-core-method/src/index.js

@daniel-van-niekerk
Copy link

daniel-van-niekerk commented Feb 27, 2018

Using 1.0.0-beta.27. This happens consistently but the transactions are mined normally.
I'm not deploying a contract here, just call a ERC20 token contract's transfer function.

This error is interfering with my error handling for actual errors. Is there no update or more info on this issue?

@TrejGun
Copy link

TrejGun commented Feb 28, 2018

same here

@zachgoll
Copy link

+1 on this. Running 1.0.0-beta.26 getting this error while using infura on Ropsten. Contracts will deploy fine, but error is thrown in promise catch.

@adonley
Copy link
Contributor

adonley commented Mar 1, 2018

This issue is woven into the web3-core-method package. There is a mix of ideas - one of pub/sub (you get a block) and one of an interval set (polling every second) which use the same catch block. We'd have to make another request to check and compare block number changes when we're doing the interval in order to prevent this from happening in 50 seconds. I'm not sure if the fix is worth the second RPC. Maybe we just make the timeout longer for polling.

@mckapur
Copy link

mckapur commented Mar 20, 2018

Even though this isn't broken on beta.31, I'm seeing an issue where I deploy a contract and -- even though the contract successfully deployed -- I'll get an error saying "The contract code couldn't be stored, please check your gas limit"

@adonley
Copy link
Contributor

adonley commented Mar 20, 2018

Try looking at trufflesuite/truffle#476 .

@NoChance777
Copy link

+1 Join to same issue. Why you guys don't make up it configurable?

@CQBinh
Copy link

CQBinh commented Jun 6, 2018

Same on bate.34, ropsten test net.

@adonley
Copy link
Contributor

adonley commented Jun 6, 2018

Web3 is mostly not configurable beyond the provider.

@CQBinh why not use a higher gasprice to be included in a block within 750 seconds on ropsten?

@CQBinh
Copy link

CQBinh commented Jun 7, 2018

@adonley I have increased the gas limit to 3,000,000 with no luck, both beta.31 and beta.34.
Here is my code:

var contractAddress = '0xd4...';
var txOptions = {
  nonce: web3.utils.toHex(web3.eth.getTransactionCount(address)),
  gasLimit: web3.utils.toHex(3000000),
  gasPrice: web3.utils.toHex(99000000000),
  to: contractAddress
}

var destinationAddress = '0xa91...';
var tokenQuantity = 69;
var rawTx = txutils.functionTx(interface, 'transfer', [destinationAddress, tokenQuantity], txOptions);
sendRaw(rawTx);

And the sendRaw function:

var address = '0xa98...';
var key = 'a84...';

function sendRaw(rawTx) {
  var privateKey = new Buffer(key, 'hex');
  var transaction = new tx(rawTx);
  transaction.sign(privateKey);
  var serializedTx = transaction.serialize().toString('hex');
  web3.eth.sendSignedTransaction(
    '0x' + serializedTx, function(err, result) {
      if(err) {
        console.log(err);
      } else {
        console.log(result);
      }
    }).on('receipt', console.log);
}

@CQBinh
Copy link

CQBinh commented Jun 7, 2018

Finally found out my issue, the web3.eth.getTransactionCount(address) is async, so I have to await or use callback or promise to get the transactionCount.

@thinhlvv
Copy link

The same issue here with web3@1.0.0-beta.34

Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!

I tried many options to remove but it's still there:

  • Add nonce to raw transaction
  • Increase gas Price/gas limit.

@CQBinh
Copy link

CQBinh commented Jun 19, 2018

@thinhlvv when connecting to the testnet, you maybe provide the exact chainId (Ropsten is 3, took from docs).
Take a look on my code:

web3.eth.getTransactionCount(address).then(txCount => {
  var txOptions = {
    chainId: 3,
    nonce: web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(51000),
    gasPrice: web3.utils.toHex(41e9),
    to: contractAddress
  }
  console.log('txOptions', txOptions)
  var destinationAddress = '0xa';
  var tokenQuantity = 69e18;
  var rawTx = txutils.functionTx(interface, 'transfer', [destinationAddress, tokenQuantity], txOptions);
  sendRaw(rawTx);
});

@thinhlvv
Copy link

thinhlvv commented Jun 19, 2018

@CQBinh Yes, I noted the chainID. I got this problem in mainnet. I ran for days, then this error appeared.

@CQBinh
Copy link

CQBinh commented Jun 19, 2018

@thinhlvv Is there the problem in the GAS limit, did you tried to increase it?

@dbryan0516
Copy link

I encountered the error
Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!

While using a private chain with geth/poa/5second blocks and trying to call a smart contract function.

I was using the lastest block's gasLimit as the gasLimit for the tx I was creating. The issue stems from the block's decreasing gasLimit as the block tries to approach the targetGasLimit that was used to create the chain. In my case (and mainnet), the targetGasLimit was 4,712,388 but the genesis block's gas limit was extremely higher, causing blocks to have a decreasing gas limit until it reached close to the targetGasLimit.

So by using the latest Block's gasLimit, by the time my tx was sent, the new block gasLimit had decreased. For some reason this never threw a "Exceed's block gas limit" error, so the tx just sat, perpetually waiting.

This was in a blockchain 101 application, very small and local app. So I would be the only one sending tx's, i didn't know how much gas would be used (estimate=infinite), so I set it to the 4.7million targetGasBlock and this seems to have fixed for now.

I'm curious as to why no other error was thrown, like "Exceeds block gas limit"

using 1.0.0-beta.34

@NicolaOrritos
Copy link

This bug is still present in 1.0.0-beta.36, but NOT in 1.0.0-beta.34.
Found while working on a private chain with PoA.
Worked around pinning to 1.0.0-beta.34 in my package.json.

@cosander
Copy link

@NicolaOrritos: Thanks for the tip, downgrading to 1.0.0-beta.34 worked for me (also with private chain with PoA and other contracts could be deployed though).
Hope this is going to be fixed sometime soon.

@NicolaOrritos
Copy link

@cosander glad it helped.
In general I also hope the developers will make web3.js return proper messages when errors occur.

@nivida
Copy link
Contributor

nivida commented Oct 25, 2018

@NicolaOrritos I've planned to create more specific error messages. I had a look on the winston logger but I think I will implement a simple logger class by my self and improve the messages. If it makes you wonder what I'm working on right now then check out this PR #2000

@ltfschoen
Copy link
Contributor

ltfschoen commented Mar 30, 2020

I encountered the same error Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined! when I'd run tests that I'd written with truffle test when was running a development chain, and where I was explicitly specifying a block time with ganache-cli --blockTime 3. I resolved the error by omitting the block time flag (i.e. just running ganache-cli) so the blocks would be mined instantly

@aenhsaihan
Copy link

aenhsaihan commented Nov 23, 2020

Is this really resolved? I'm still getting the same error on 1.2.2

I get the error when I used Kovan testnet just now. But for local development with instant mining, the await function never returns so the page just shows the transaction as still processing.

@SilvioGuedes
Copy link

SilvioGuedes commented Apr 15, 2021

Guys, the problem is still happening in 1.3.5:

   const web3Eth = Utils.getWeb3Eth(apiKey, network)
    const nonce = await web3Eth.getTransactionCount(userAddress, 'pending');
    const block = await web3Eth.getBlock("latest")
    const gasLimit = block.gasLimit
    const gasUsed = block.gasUsed

    const txParams = {
        gasPrice: web3Utils.toHex(gasPrice),
        gasLimit: web3Utils.toHex(gasLimit),
        gas: web3Utils.toHex(gasUsed),
        from: userAddress,
        nonce: web3Utils.toHex(nonce),
        to: smartContractAddress,
        data: contract.methods.setBaseURI(baseURI).encodeABI(),
    };

    try{
        const tx = new Tx(txParams, {'chain':network});
        privateKey = stripHexPrefix(privateKey)
        const privateKeyBuffer = Buffer.from(privateKey,'hex')
        tx.sign(privateKeyBuffer);
        const serializedTx = tx.serialize();
        
        await web3Eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
            .on('transactionHash', function(hash){
                console.log("hash "+hash)
            })
            .on('confirmation', function(confirmationNumber, receipt){
                console.log("confirmationNumber "+confirmationNumber)
            })
            .on('error', function(e){
                console.log("error "+e)
            })
            .then(function(receipt) {
                console.log(receipt)
            })
    }
    catch (e) {
        console.log("error "+e)
    }

Only the callback 'transactionHash' is fired and the transaction, that is showed on console, is no visible on Etherscan.
Example: https://rinkeby.etherscan.io/tx/0x1f5451fab88b32a4363e299ddcf64ad29d14871e105bbfd97bc3189e4c33615c.

The weird thing is the account 0x64... has this problem, but my other account (0x58...) hasn't using the same code and also the same settings for transaction!

Information:

  • Network: Rinkeby;
  • API: Infura;
  • Version Web3: 1.3.5;
  • Gas Price: 2000000000;
  • Gas Limit: 10000000.

If you need more details, please tell me. Thanks in advance!

@rellfy
Copy link

rellfy commented Apr 15, 2021

The weird thing is the account 0x64AB5021e2553fE1791e88E540092eBA3599DE7B has this problem, but my other account (0x581ec6402aa109bccaff7ab4d6143aaebd08152c) hasn't using the same code and also the same settings for transaction!

@oivlisnet I have the same exact issue. I was not aware it only happens on a specific account, so thanks for pointing that out. It is very strange indeed, I'm curious to know what's causing this. It only happens with web3 as I tried with ethers.js and the issue doesn't happen there. Must be some local issue maybe?

@SilvioGuedes
Copy link

SilvioGuedes commented Apr 15, 2021

@rellfy Hi! No, I am not using MetaMask, I am using privateKey directly in the transaction:

privateKey = stripHexPrefix(privateKey)
const privateKeyBuffer = Buffer.from(privateKey,'hex')
tx.sign(privateKeyBuffer);

I forgot to put the contract address, but this error happens in any smart contract address for the account 0x64... if I mint something. I can't use this account since block 8408011.

Thanks for the tip, I'll try the ethers.js and I'll put here if it worked or not.

@SilvioGuedes
Copy link

SilvioGuedes commented Apr 17, 2021

@rellfy Thanks for the tip about ethers, it worked!

The code:

    const provider = new ethers.providers.JsonRpcProvider(
        "https://" + network + ".infura.io/v3/" + apiKey,
    );
    const nonce = await provider.getTransactionCount(userAddress, 'pending')
    const block = await provider.getBlock("latest")
    const gasLimit = block.gasLimit

    try{
        const wallet = new ethers.Wallet(privateKey, provider);
        const contract = new ethers.Contract(smartContractAddress, abi, wallet);
        const tx = await contract.setBaseURI(baseURI,{
            gasPrice: web3Utils.toHex(gasPrice),
            gasLimit: gasLimit,
            nonce: nonce
        })
        console.log("Waiting Transaction "+tx.hash);
        await tx.wait().then(
            () => {
                console.log("Transaction mined: "+tx.hash)
            },
            e => {
                console.log("error "+e)
            })
    }
    catch (e) {
        console.log("error "+e)
    }

Now I can deploy and mint with other account.
With web3, this account still has the same problem, I don't know why.

@LinSays
Copy link

LinSays commented Apr 25, 2022

I still got error on sending transaction with web3 though I didn't use 'await'. Could you help me with this? My skype id is: live:.cid.41555bb2f81e56cb. Hope you can directly teach me a lesson. Best regards

@soohanpark
Copy link

soohanpark commented Jul 6, 2022

Hi, There ✋

This is already closed, but I think I found a solution in official docs.

Increase transactonBlockTimeout like an example in below link.
https://web3js.readthedocs.io/en/v1.7.4/web3-eth.html#transactionblocktimeout

(++ Also, maybe I guess we should increase transactionPollingTimeout, too.)
https://web3js.readthedocs.io/en/v1.7.4/web3-eth.html#transactionpollingtimeout

@EmperorRP
Copy link

I got this error on metamask when I was trying to solve some Ethernaut challenges. My simple fix was to cancel all the pending transactions and retry your transaction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.