3

How to send multiple transactions which will be mined in one block in Hardhat tests?

3 Answers 3

3

check the mining behavior here

networks: {
  hardhat: {
    mining: {
      auto: false,
      interval: 5000
    }
  }
}

In this example, automining is disabled and interval mining is set so that a new block is generated every 5 seconds. You can also configure interval mining to generate a new block after a random delay:

Manual mining

You can disable both mining modes like this:

networks: {
  hardhat: {
    mining: {
      auto: false,
      interval: 0
    }
  }
}

This means that no new blocks will be mined by the Hardhat Network, but you can manually mine new blocks using the evm_mine RPC method. This will generate a new block that will include as many pending transactions as possible.

you can also use this plugin to handle the mining modes

block.setAutomine(enabled: boolean)

block.setIntervalMine(interval: number | BigNumber)

1
  • 1
    I tried with manual mining. Still transactions are mined one per block
    – misterio
    Commented Jun 20, 2022 at 23:17
2

I was able to follow the response from @Javier Marchetti and send multiple transactions to be mined in the same block. I manually mined the block using evm_setAutomine and evm_setIntervalMining with interval set to "0" in runtime instead of doing it in the configuration file. Then sent the block mine command using RPC method "evm_mine". Here is the summary code

  await network.provider.send("evm_setAutomine", [false]);
  await network.provider.send("evm_setIntervalMining", [0]);
  // SEND TRANSACTION 1

  // SEND TRANSACTION 2
  await network.provider.send("evm_mine");

You can check the block numbers for both transactions by console logging them using hardhat console.sol import to verify the transactions were mined in the same block.

1

The other answers have provided insight into configurations and methods for mining multiple transactions in a single block. I'd like to extend this by offering an example of:

How to write a Hardhat test that must revert and involves mining multiple transactions in one block?

Utilizing await network.provider.send("evm_mine"); can't be paired with the expect().to.be.revertedWith() statement.

Here's how you can achieve this:

await network.provider.send("evm_setAutomine", [false]);
// SEND TRANSACTION 1
// SEND TRANSACTION 2

await network.provider.send("evm_setAutomine", [true]);
await expect(<SEND TRANSACTION 3>).to.be.revertedWith("Three tx's in the same block");

Returning to auto mine doesn't execute the pending transactions immediately. However, the transactions are executed when the next transaction is dispatched.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.