question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to catch events with provider when using Ganache-Core for test

See original GitHub issue

I am writing a test to listen to events on the blockchain, most especially the ‘block’ event. My tools are Ethers.js and Ganache-core. Using the provider.on(event, callback) function does not work. here is a copy of my code and what I was testing:

const ethers = require('ethers');
const getProvider = new ethers.providers.Web3Provider(ganache.provider({mnemonic: some random phrase}));

describe('listen to blockchain transactions', () => {
 beforeAll(async (done) => {
        provider = getProvider();
  });
 afterAll(async () => {
        provider.stop();
 });

it('should listen to transactions between user accounts', async () => {
        const accounts = await provider.listAccounts();
        const userAccount1 = accounts[1];
        const userAccount2 = accounts[2];
        const chainId = (await provider.ready).chainId;
        let transaction = {
            nonce: 0,
            gasLimit: 21000,
            gasPrice: ethers.utils.bigNumberify("20000000000"),
            to: userAccount2,
            value: ethers.utils.parseEther("10.0"),
            data: "0x",
            chainId: chainId
        };
        const privateKey = await accountService.getAccountSigningKey(userAccount1);
        const wallet = new ethers.Wallet(privateKey);
        const signedTransaction = await wallet.sign(transaction);
        const transactionResponse = await provider.sendTransaction(signedTransaction);
        provider.on('block', async (blockHeight) => {
            console.log('blockHeight: ', blockHeight) //Nothing logs, this callback is not executed    
        });
    });
})

Could there be a better way to do this? Kindly recommend.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:18 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
zemsecommented, May 26, 2021

The way contract.on("Transfer", cb); works is it polls the chain in intervals (default 4 secs).

it('test case', async () => {
  const contract = ...; // declare

  contract.on("Transfer", cb); // 0ms

  await contract.transfer(...args); // 100ms
}) // contract variable scope is finished, it is cleared

As you can see your test case runs for such a small time, then moves to another test case. If you want to make that work, you might try waiting until the polling interval (also shortening the polling interval).

await new Promise(res => setTimeout(res, 4000)); // waits for 4 secs

However, to test events, I’d suggest to instead use an alternate method that doesn’t need you to wait.

it('testcase', async() => {
  const tx = await contract.transfer(...args); // 100ms
  const rc = await tx.wait(); // 0ms, as tx is already confirmed
  const event = rc.events.find(event => event.event === 'Transfer');
  const [from, to, value] = event.args;
  console.log(from, to, value);
})
1reaction
andrewgordstewartcommented, Oct 23, 2019

Ok… I will address this somehow… I need to think of a better way to do this.

The problem is that in a PoA network, which is what Ganache basically is, there are no blocks mined if there is nothing happening. And since ethers only triggers an event processing loop when a block happens, this never happens in a non-chatty PoA network.

Is there a way to make ganache mine empty blocks periodically? This should also “help” the situation, but isn’t a real fix. I’ll think about this for a bit too…

Ganache does offer this feature with the --blockTime flag: npx ganache-cli --blockTime n will mine a block every n seconds.

If you don’t want to do this, you can also manually mine a block by sending evm_mine. Here’s a blog post that uses this technique.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to catch events with provider when using Ganache ...
My tools are Ethers.js and Ganache-core. Using the provider.on(event, callback) function does not work. here is a copy of my code and what...
Read more >
Unable to subscribe to web3js event due to provider
I am using Ganache as a test node. truffle-config.js: networks: { ganache: { host: "localhost", // Localhost (default: none) port: ...
Read more >
ConsenSys/truffle - Gitter
Hey guys, I have issues with catching events when using ganache-core for testing. The description of my problem is here: ethers-io/ethers.js#615.
Read more >
How to use the ethers.providers function in ethers - Snyk
To help you get started, we've selected a few ethers.providers examples, ... catch (err) { console.warn(`Unable to connect via Web3 provider`, ...
Read more >
Transaction simulation - Forta Docs
Using simulation, you can run transactions from any account on the latest ... catch (e) { // report a finding if the simulated...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found