Web3 can be used on browser as well as server side. This example is going to use Nodejs on server side. Also, I've used Ubuntu to do this example but it should be valid for Windows as well.
In this example, we are going to watch the event every time a CryptoKitty is born. This example assumes that you have Nodejs installed on your system.
- Make a directory wherever you want to create.
- Switch to directory Ethereum-Subscription-APIs and initialize an nodejs project like below.
- Select all default options like below
After successful initialization you will see a file being created "package.json"
- Now install web3
npm install web3 -save
Now create a file "index.js"
Now, let's put together some code in index.js
Let's go break apart the code in above screenshot to understand it better.
Line no 5 in above screenshot:-
this.web3 = new Web3(url?url:"wss://mainnet.infura.io/_ws");
I am using end point provided by Infura to connect to geth instace , you can also use your local geth instance if you want.
Line no 12 in above screenshot:-
This is the address of CryptoKitty contract deployed on Ethereum network. you can have a look on contract on etherscan.io.
line no 13 in above screenshot:-
This is the topic that we want to watch to see birth of cryto kitty.
What is topic?
It's nothing but keccak hash of event signature which gets fired every time "_createKitty" function of the contract is executed.
Let's run the code now. I have checked-in the code at GitHub and instruction to run the code. I have also included the code on GitHub on how to watch pending transaction using subscription API.
There are other useful subscription API, you can see the list here
Read more articles at EtherWorld's collection of Good Read on Blockchain & Cryptocurrency.
Follow us at Twitter, Facebook, Googe+, Medium and Steemit.
For weekly round up on Ethereum and other blockchain news, technology and projects, subscribe EtherWorld's Blockchain Weekly .____________________________________________________________________________________________________