Search code examples
javascripteventshyperledger-fabrichyperledgerhyperledger-chaincode

How to add events in chaincode? (Hyperledger Fabric)


I am trying to make events work in Hyperledger Fabric. I have written the setEvent function in my chaincode and added a listener (addContractListener) in my application file. Nothing seems to happen

In my contract file, right after a putState function :

await this.ctx.stub.setEvent('event1', data);

In my application file, right after the submitTransaction function:

let eventTxn = await contract.addContractListener('some-string', 'trade-network',
        (err, event, blkNum, txid, status) => {
            console.log('event received', status, event, blkNum, txid);
            if (err) {
                this.emit('error', err);
            } else if (status && status === 'VALID') {
                // only if a valid block is committed should we emit an event
                let evt = event.payload.toString('utf8');
                evt = JSON.parse(evt);
                if (Array.isArray(evt)) {
                    for(const oneEvent of evt) {
                        this.emit('ChaincodeEvent', oneEvent);
                    }
                }
                else {
                    this.emit('ChaincodeEvent', evt);
                }
            }
       },
       {filtered: false}
    );

I have added the above lines of code in my contract and application. On executing the application function, nothing seems to happen and the program is stuck returning no response. Even the 'console.log' isn't executed which means it didnt enter the function fully.

I was expecting the application function to get executed. Could someone guide me as to how to make a simple event work in Hyperledger Fabric?


Solution

  • Maybe there is a mismatch between the name of the event of the chaincode event1 and the event that you are listening to trade-network