> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

# subscribe ("logs") | Polygon

> Reference for the subscribe ("logs") JSON-RPC method on the Polygon blockchain via Chainstack nodes. Parameters, response, and examples included.

Subscription equivalent to [eth\_newFilter | Polygon](/reference/newfilter). `subscribe("logs")` allows developers to subscribe to real-time updates about new event logs on the Polygon blockchain; the application will receive notifications whenever new logs matching the filter are emitted.

## Parameters

* `string` — a keyword identifying the type of event to subscribe to, `logs` in this case.

* `object` — (optional) the subscription options:

  * `fromBlock` — an integer that specifies the starting block number from which the logs should be fetched. `null` by default.
  * `address` — the contract address from which the logs should be fetched. It can be a single address or an array of addresses.
  * `topics` — an array of `DATA` topics. The event topics for which the logs should be fetched. It can be a single topic or an array of topics.

* `function` — (optional) a callback function that will be called every time a new event of the specified type is received. This function takes two parameters: `error` and `result`. The error parameter contains any error that occurred while subscribing to the event, and the result parameter contains the data for the event that was received.

## Response

* `array` — an array of log objects that match the specified filter:

  * `address` — the contract address from which the event originated.
  * `topics` — an array of 32-byte data fields containing indexed event parameters.
  * `data` — the non-indexed data that was emitted along with the event.
  * `blocknumber` — the block number in which the event was included. `null` if it is pending.
  * `transactionhash` — the hash of the transaction that triggered the event. `null` if pending.
  * `transactionindex` — the integer index of the transaction within the block's list of transactions. `null` if it is pending.
  * `blockhash` — the hash of the block in which the event was included. `null` if it is pending.
  * `logindex` — the integer identifying the index of the event within the block's list of events. `null` if pending.
  * `removed` — the boolean value indicating if the event was removed from the blockchain due to a chain reorganization. `True` if the log was removed. `False` if it is a valid log.

## `subscribe("logs")` code example

<Info>
  Note that subscriptions require a WebSocket connection.
</Info>

Use a `WebSocketProvider` and attach a listener to a log filter object:

* The listener callback activates for each new log that matches the filter.
* Wrap the subscription in a `try...catch` block to detect any error during setup.
* `provider.removeAllListeners(filter)` removes the listener and stops the subscription.

<CodeGroup>
  ```javascript index.js theme={"system"}
  const { ethers } = require("ethers");
  const NODE_URL = "CHAINSTACK_WSS_URL";
  const provider = new ethers.WebSocketProvider(NODE_URL);

  // Only log transfer events from the WMATIC smart contract.
  const logsFilter = {
      address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
      topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef']
  }

  async function subscribeToLogs() {
      try {
          // Create a new subscription to the logs matching the filter
          provider.on(logsFilter, handleLogs);
          console.log("Subscribed to logs");
      } catch (error) {
          console.error(`Error subscribing to new logs: ${error}`);
      }
  }

  /* Listener functions to react to the different events */

  // Event listener that logs the filtered events
  function handleLogs(log) {
      console.log(log)
  }

  subscribeToLogs();
  ```
</CodeGroup>

## Use case

A practical use case for `subscribe("logs")` is a DApp that continuously listens for new specific event logs and isolates certain fields for analytics purposes. This is useful, for example, to only track events about a specific ERC-721 token.

The following is an implementation of this concept using ethers.js subscriptions, this program will only track the `PunkTransfer` event from the [PolygonPunks collection](https://polygonscan.com/token/0x9498274B8C82B4a3127D67839F2127F2Ae9753f4#code) smart contract.

The `PunkTransfer` event looks like this in the smart contract:

<CodeGroup>
  ```sol PolygonPunksMarket.sol theme={"system"}
  event PunkTransfer(address indexed from, address indexed to, uint256 punkIndex);
  ```
</CodeGroup>

The following code will log all of the new `PunkTransfer` events and extract the block number. This can be useful to analyze when tokens are moved.

<CodeGroup>
  ```javascript index.js theme={"system"}
  const { ethers } = require("ethers");
  const NODE_URL = "CHAINSTACK_WSS_URL";
  const provider = new ethers.WebSocketProvider(NODE_URL);

  // Only log PunkTransfer events from the Polygon Punks smart contract.
  const logsFilter = {
      address: '0x9498274B8C82B4a3127D67839F2127F2Ae9753f4',
      topics: ['0x05af636b70da6819000c49f85b21fa82081c632069bb626f30932034099107d8']
  }

  async function subscribeToLogs() {
      try {
          // Create a new subscription to the logs matching the filter
          provider.on(logsFilter, handleLogs);
          console.log("Subscribed to logs");
      } catch (error) {
          console.error(`Error subscribing to new logs: ${error}`);
      }
  }

  // Use this function to unsubscribe and exit the program
  function unsubscribe() {
      provider.removeAllListeners(logsFilter);
      console.log("Successfully unsubscribed!");
      return process.exit(1);
  }

  /* Listener functions to react to the different events */

  // Event listener that logs the filtered events
  async function handleLogs(log) {
      const block = log.blockNumber
      console.log(`A Polygon Punk was transferred in this block: ${block}`)
  }

  subscribeToLogs();
  ```
</CodeGroup>

This code creates a new subscription to the logs matching the filter using the `provider.on` method with a `WebSocketProvider`. This method attaches a listener that is called for each new log matching the filter.

The code defines the `handleLogs` listener function that is attached to the provider. The `handleLogs` function is called when a new log matching the filter is emitted, then extracts the block number field and logs it to the console. The subscription setup is wrapped in a `try...catch` block to detect any error during setup.

The code includes the `unsubscribe` function that can be implemented in the logic to remove the listener with `provider.removeAllListeners` and exit the program when a condition is met.

Finally, the code calls the `subscribeToLogs` function, which creates the subscription and attaches the event listeners. When a new event log is received, the `handleLogs` function is called to extract the data and log it to the console.

## Try the `subscribe("logs")` RPC method yourself
