txpool.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const { network } = require('hardhat');
  2. const { promisify } = require('util');
  3. const queue = promisify(setImmediate);
  4. async function countPendingTransactions () {
  5. return parseInt(
  6. await network.provider.send('eth_getBlockTransactionCountByNumber', ['pending']),
  7. );
  8. }
  9. async function batchInBlock (txs) {
  10. try {
  11. // disable auto-mining
  12. await network.provider.send('evm_setAutomine', [false]);
  13. // send all transactions
  14. const promises = txs.map(fn => fn());
  15. // wait for node to have all pending transactions
  16. while (txs.length > await countPendingTransactions()) {
  17. await queue();
  18. }
  19. // mine one block
  20. await network.provider.send('evm_mine');
  21. // fetch receipts
  22. const receipts = await Promise.all(promises);
  23. // Sanity check, all tx should be in the same block
  24. const minedBlocks = new Set(receipts.map(({ receipt }) => receipt.blockNumber));
  25. expect(minedBlocks.size).to.equal(1);
  26. return receipts;
  27. } finally {
  28. // enable auto-mining
  29. await network.provider.send('evm_setAutomine', [true]);
  30. }
  31. }
  32. module.exports = {
  33. countPendingTransactions,
  34. batchInBlock,
  35. };