hedera-hashgraphhashgraph

Where does one access events that are emitted from a solidity contract, either via a node or a mirror?


How can I get emitted events from a solidity smart contract on the Hedera Network? My best guess is via ContractFunctionResult.


Solution

  • You have few options:

    1. Use hether.js, so something like:
    // Setup a filter and event listener to know when an address receives/sends tokens
    const filter = contract.filters.Transfer(walletAddress, null);
    
    contract.once(filter, (from, to, amount, event) => {
      console.log(`\n- Event: ${from} sent ${amount} tokens to ${to}`);
    });
    

    More on hether.js events here: https://docs.hedera.com/hethers/application-programming-interface/contract-interaction/contract#events

    1. You can use ethers.js or web3.js with the Hedera SDKs to parse event logs, either from transaction records or mirror node api results. So, to get event data in a readable fashion you would use the contract’s ABI, log data, and ethers/web.js. Here's some sample JS code using ethers.js and mirror node (can do something similar with info from the tx record):

      async function getEventsFromMirror(contractId) {
       const url = https://testnet.mirrornode.hedera.com/api/v1/contracts/${contractId.toString()}/results/logs?order=asc;
      
       axios.get(url)
           .then(function (response) {
               const jsonResponse = response.data;
      
               jsonResponse.logs.forEach(log => {
                   // create an object to specify log parsing requirements
                   let logRequest = {};
                   logRequest.data = log.data;
                   logRequest.topics = log.topics;
                   // parse the logs
                   let event = abiInterface.parseLog(logRequest);
                   // output the from address and message stored in the event
                   console.log(Mirror event(s): from '${AccountId.fromSolidityAddress(event.args.from).toString()}' update to '${event.args.message}');
               });
           })
           .catch(function (err) {
               console.error(err);
           });
      

    }

    1. Get the logs and events directly from a mirror node (https://hips.hedera.com/hip/hip-226 and https://hips.hedera.com/hip/hip-227) and use your own library, if applicable. Probably the first two options make more sense for most folks.