How to use WebSocket Subscriptions with the Infura Polygon WSS API

Learn how to harness the power of WebSocket subscriptions with the Infura Polygon WSS API tutorial.

How to use WebSocket Subscriptions with the Infura Polygon WSS API

Learn how to harness the power of WebSocket subscriptions with the Infura Polygon WSS API tutorial.

The true benefit of WebSocket subscriptions for developers building on blockchains with Infura is the ability to establish a persistent connection, enabling real-time updates between a client and a server. In contrast, with stateless requests over the HTTP protocol, developers need to continuously poll  APIs for updates.

WebSockets are now available as public beta via the Infura Polygon WSS API. With WebSocket subscriptions, developers can conveniently subscribe to events and directly receive information in their applications.  This allows you to:

  • Monitor new pending transactions for specific trading activity.
  • Stay updated with the latest block information by receiving new block headers.
  • Listen for updates to smart contracts, such as new NFT mintings or balance checks, by subscribing to logs.

To help you get started with using the Infura Polygon WebSocket, here’s a tutorial on how to subscribe to new pending transactions on the Polygon network.

Part one: Create an Infura Account and activate Polygon WebSocket

Following these steps to create an Infura account and activate the Polygon WebSocket for your account:

  1. Create an Infura account and log in to your Infura dashboard.
  2. Add Polygon as your desired network (it is free).
  3. Choose the project you intend to use or create a new one.
  4. Locate your API keys, which are typically listed under a project name as shown below:

5.  Select "ACTIVATE ADD ON" for Polygon and follow the prompt. Note that there will be no charges to your card.

6. Now with Polygon activated, navigate to the "WSS" tab to see the WebSockets API endpoint.

Part two: Create a new Python project and install dependencies

Follow these steps to install Python on your machine if you don't already have it installed:

  1. Set up your development environment, and ensure you have Python installed on your machine.
  2. Create a new project directory "subscribe" and navigate into it:
mkdir subscribe
cd subscribe

3. Install the web3.py and WebSockets libraries by running the command:

pip install web3 websockets

4. In the newly created "subscribe" directory, create a new file "subscribe.py" and import the necessary libraries:

import asyncio
import json
import requests
from web3 import Web3
from websockets import connect

Part three: Subscribe to pending transactions

Create an async method that connects to Infura’s Polygon WebSocket endpoint and subscribes to new pending transactions:

...

infura_ws_url = wss://polygon-mainnet.infura.io/ws/v3/<YOUR_API_KEY>'

async def get_event():
    async with connect(infura_ws_url) as ws:
        await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}')
        subscription_response = await ws.recv()
        print(subscription_response) #{"jsonrpc":"2.0","id":1,"result":"0xd67da23f62a01f58042bc73d3f1c8936"}

Please ensure you replace <YOUR_API_KEY> with your Infura API key.

In the method above, we use ws.send() to start a new subscription for new pending transactions, after which we get a confirmation back from the node with our subscription ID.

Finally, we await any new messages from the Infura node and print the transaction hash of every new transaction appearing on the Polygon chain.

Start using the Polygon Websocket today

WebSocket subscriptions through the Infura Polygon WSS API provide developers with a solution for real-time updates. By establishing a persistent connection, developers can avoid the need for continuous polling and instead conveniently subscribe to events and receive information directly in their applications.                  

Refer to the Infura documentation for more information on how you can enhance your dapp using Polygon WebSocket.