Tutorial A9: Publishing An Event: 30 Minutes
Tutorial A9: Publishing An Event: 30 Minutes
In Hyperledger Fabric, smart contracts can generate events that can be received by applications that have
registered for event notifications. In this tutorial we will:
In order to successfully complete this tutorial, you must have first completed tutorial A5: Invoking a smart
contract from an external application in the active workspace. It is desirable to have completed up to tutorial
A8: Testing a smart contract.
So far in this tutorial series, applications that submit new transactions are closely coupled to applications that
query the ledger. For example, one application has to submit a transaction and let consensus complete
before another application can query the ledger to confirm the result of that transaction.
An alternative pattern to couple applications connected to a Hyperledger Fabric network is using events and
notifications. Applications can call smart contracts which generate transactions containing an event, and
when that transaction is successfully committed to the ledger, a notification can be received by one or more
applications that have registered for event notification. This is a loosely coupled paradigm; the event
consumer is unaware of the event producer.
An event is used to describe any significant situation that will be of interest to one or more applications; for
example, when an update to an asset has occurred. Indeed, it can be appropriate to use this style of
application coupling in many different scenarios:
A transaction generated by a smart contract can include an event. When the transaction is committed to the
ledger, all applications that are connected a suitable peer will receive a notification of this event. This is the
publish/subscribe metaphor; a smart contract generates an event that can be consumed by zero or more
applications. Applications can come and go; the event consumer and event producer are said to be loosely
coupled to each other.
As well as smart contract events, Hyperledger Fabric components can also publish system events when
interesting things occur, such as when a block is committed.
Before we can register for event notifications, we first need a smart contract with a transaction containing an
event. We will use the 'createMyAsset' transaction in the smart contract we previously created to do this.
If the file is not already open, use the Explorer side bar to navigate to 'demo-contract' -> 'src' -> 'my-asset-
contract.ts'.
A9.3: Navigate to the 'createMyAsset' method and use copy and paste to insert the following two
lines at the end of the transaction's implementation:
The setEvent method takes two parameters: in our example, we see an event name (the string "myEvent")
and the event payload (a buffer containing the text "Created asset" and some details of the asset. We'll refer
to this information again a little later.
A9.5: Switch to the 'demo-contract' -> 'package.json' editor and update the value of the "version"
field to "0.0.3".
A9.7: Hover over the Smart Contracts view in the IBM Blockchain Platform side bar, click the ellipsis
(...) and select 'Package Open Project' for the 'demo-contract' project.
Wait a few seconds for the v0.0.3 smart contract to be built and shown in the Smart Contracts view.
A9.8: In the Fabric Environments view, expand "mychannel" and click "+ Deploy smart contract".
A9.9: In the Deploy Smart Contract form Step 1, select "[email protected]" from the drop down
list, and click 'Next'.
A9.10: In step 2 of the Deploy Smart Contract form, default values for Definition name and version
of the updated contract are provided, click 'Next'.
You may need to wait a minute or so for the deployment of the upgraded smart contract to complete.
The upgraded version of the smart contract will be displayed in the Fabric Environments view under
mychannel.
With this change to the smart contract, every time a 'createMyAsset' transaction is committed, an event
notification will sent to all applications registered for this event.
Smart contract notifications are only generated when a transaction containing an event is valid; an invalid
transaction will not result in an event notification of the event within the transaction. Also, read-only
transactions cannot generate events.
Any authorized client application can request event notification. It is possible request event notification within
the IBM Blockchain Platform VS Code extension. Let's do that now.
A9.13: In the Fabric Gateways view, ensure that the local gateway is connected.
If the gateway is disconnected, click on "1 Org Local Fabric - Org1 Gateway" in this view to connect.
A9.14: Right-click '[email protected]' and select 'Subscribe to Events'.
We need to specify which event(s) we are interested in. As you will recall from our event emission code, we
named our topic 'myEvent'.
You will see a notification that confirms that the subscription has been registered.
Now that we have successfully subscribed to the 'myEvent' topic, we'll be able to receive notifications of those
events in the VS Code output console.
A9.18: Select createMyAsset as the Transaction name and supply the JSON Transaction arguments
{"myAssetId": "004","value": "Dogs Playing Poker"}.
A9.19: There is no transient data and no peer selection required, just click Submit transaction.
The Output panel will show not only the transaction output, but also information about the event that was
emitted.
This information is only displayed because of the active subscription. The subscription will persist until the
gateway is disconnected.
We will now try and subscribe to the same topic from within a client application. We will create a listener.ts
client application that will be part of the project we created in tutorial A5: Invoking a smart contract from an
external application.
A9.21: Switch to the Explorer view, and right click the 'src' folder underneath 'demo-application'.
Select 'New File'.
A9.22: Name the file 'listener.ts' and press Enter to load the new file in the editor.
A9.23: Copy and paste the following source code into the new file. (It is also available here.)
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}
void main();
If you completed tutorial A5: Invoking a smart contract from an external application in the same VS Code
session, the compiler will be in watch mode, and the application will now rebuild itself and you can skip to
A9.26.
A9.25: If necessary, rebuild the client application by clicking 'Terminal' -> 'Run Build Task' and
selecting 'tsc: watch - tsconfig.json demo-application'.
We will now run the application using an npm script that we created in tutorial A5: Invoking a smart contract
from an external application. When we created our package.json file in this tutorial, we included an npm script
called 'listener' that will run our new application:
A9.26: Click 'Terminal' -> 'Run Task', and find and select 'npm: listener demo-application'.
As always, take care in selecting the correct task as the options can look alike.
A9.27: As before, select the option to continue without scanning the output.
The client application will now run: the application will connect to the gateway, register for 'myEvent'
notifications and then pause indefinitely while it waits to receive them.
Note that we now have two subscribers: the IBM Blockchain Platform extension subscriber that we configured
earlier, and our new client application. We will now test that notifications can be received by both of them.
A9.28: Switch to the Transaction view and submit a createMyAsset Transaction with Transaction
arguments {"myAssetId": "005","value": "The Starry Night"}. As before there is no transient
data or peer selection.
The transaction will be submitted and the Output view updated with the log of the transaction. Note that it
includes the new event, which has been received and logged by the first subscriber (IBM Blockchain
Platform):
A9.30: Click the Terminal tab to show the running listener application.
Notice that the subscriber has successfully caught the event and run the handler code:
Feel free to continue trying out the event framework. When you have finished, remember to close down the
listener application:
A9.31: Right click in the running listener's terminal and select 'Kill Terminal'.
Summary
In this tutorial, we have updated one of the transactions in a smart contract to emit an event, subscribed to
this event by specifying the correct topic string, and observed the event being output to the VS Code console.
We then created a client application to subscribe to the same topic, and checked that it too could receive
events.
In the final tutorial of this set, we will summarize what we have covered so far and invite you to claim a badge
for your efforts!
→ Next: A10: Claim your badge!