Web3 subscription APIs and watching birth of CryptoKitty

Web3 subscription APIs and watching birth of CryptoKitty

Web3 provides some very useful APIs by which you can subscribe to the events on Ethereum blockchain. Web3 is a JavaScript library which interact with Ethereum node over RPC. Let's walk through a couple of subscription APIs.

Watching Events

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.

  1. Make a directory wherever you want to create.
mkdir Ethereum-Subscription-APIs
  1. Switch to directory Ethereum-Subscription-APIs and initialize an nodejs project like below.
npm init
  1. Select all default options like below


After successful initialization you will see a file being created "package.json"

  1. Now install web3
npm install web3 -save
  1. Now create a file "index.js"

  2. 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:-

 address: '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d'

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:-

 topics: ['0x0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad5']

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.

Screen-Shot-2019-03-14-at-12.23.48-PM Screen-Shot-2019-03-14-at-12.23.31-PM


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 .


Share Tweet Send
You've successfully subscribed to EtherWorld.co
Great! Next, complete checkout for full access to EtherWorld.co
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.