Search code examples
javascriptethereumsolidityweb3js

Accessing events from interface contract - Event doesn't exist in this contract


I have a contract that calls an event declared in a solidity interface.

I'd like to know how to listen to that event from Web3

import "../interfaces/Event.sol";
contract MyContract is ISEvents { 

 function emitEvent(uint32 operatorShare) external returns (bytes32 ID)
{
     emit myEvent(data);
}
}

Interface file

interface ISEvents {.
    event myEvent(
        uint256 adata
    );
}

web3 snippet

// MyContract is the web3 instance of MyContract
Myevent =MyContract.events.myEvent()
Myevent.on('data', eventcallback );

This returns: Event "myEvent" doesn't exist in this contract.

What's the way to listen to myEvent from web3. Should i deploy the instance file ? Do i have to declare the event inside my contract for accessing it externaly?


Solution

  • Yes you have to declare the event inside your contract for accessing it externally.

    As an example, consider the ERC20 smart-contract's solidity code at https://bscscan.com/address/0x2170Ed0880ac9A755fd29B2688956BD959F933F8#code

    It contains the following declared events :

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    

    To intercept these events from your web3 javascript/nodejs code you can do the following :

        const provider = new ethers.providers.JsonRpcProvider('https://bsc-dataseed.binance.org/');
        const wallet = new ethers.Wallet(privateKey)
        const account2 = wallet.connect(provider);
    
        const factory = new ethers.Contract(
        '0x2170Ed0880ac9A755fd29B2688956BD959F933F8',
        [
            'event Transfer(address indexed from, address indexed to, uint256 value)',
            'event Approval(address indexed owner, address indexed spender, uint256 value)',
        ],
        account2
        );
    
        factory.on('Transfer', async (from, to, value) => {
            console.log('transfer ' + from + ' ' + to + ' ' + value)
        })
    
        factory.on('Approval', async (owner, spender, value) => {
            console.log('approval ' + owner + ' ' + spender + ' ' + value)
        })
    

    This is for an ERC20 (BEP20) smart contract deployed on the Binance Smart Chain but this is exactly the same for the Ethereum blockchain.