> ## 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.

# eth_newFilter | Polygon

> Polygon API method that generates a filter object based on the filter parameters. Available on Polygon via Chainstack JSON-RPC nodes.

Polygon API method that generates a filter object based on the filter parameters. It returns a filter ID, which can be used to retrieve the results of the filter using the [eth\_getFilterChanges](/reference/getfilterchanges) method. By creating a filter for specific events, developers can receive notifications when those events occur and use them to trigger actions in their applications.

## Parameters

* `object` — the filter parameters:
  * `fromBlock` — (optional, default: `latest`) integer that specifies the starting block number from which the logs should be fetched.
  * `toBlock` — (optional, default: `latest`) integer that specifies the ending block number until which the logs should be fetched.
  * `address` — (optional) the contract address from which the logs should be fetched. It can be a single address or an array of addresses.
  * `topics` — (optional) 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.
  * `blockhash` — (optional) the hash of the specific block. Limits logs to a specific block with a 32-byte hash value. It takes precedence over `fromBlock` and `toBlock`.

<Note>
  **Possible tags forfromBlockandtoBlock**

  * `latest` — the most recent block in the blockchain and the current state of the blockchain at the most recent block
  * `earliest` — the earliest available or genesis block
  * `pending` — the pending state and transactions block. The current state of transactions that have been broadcast to the network but have not yet been included in a block.

  See the [default block parameter](https://eth.wiki/json-rpc/API#the-default-block-parameter).
</Note>

## Response

* `result` — a hexadecimal string representing the ID of the newly created filter

<Warning>
  The filters created are stored on the blockchain client instance. The filter is automatically deleted if not polled within a certain time (5 minutes by default).
</Warning>

Use the following methods with the filter ID:

* [eth\_getFilterChanges](/reference/getfilterchanges) to retrieve updated logs
* [eth\_uninstallFilter](/reference/uninstallfilter) to remove the filter

## `eth_newFilter` code examples

<Note>
  Note that the `web3.eth.filter` methods have been deprecated and replaced with the `web3.eth.subscribe` in web3.js. See [web3.js subscriptions](/reference/polygon-web3js-subscriptions-methods).
</Note>

<CodeGroup>
  ```javascript ethers.js theme={"system"}
  const ethers = require('ethers');
  const NODE_URL = "CHAINSTACK_NODE_URL";
  const provider = new ethers.JsonRpcProvider(NODE_URL);

  const filter = {
    toBlock: 'latest',
    address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
    topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef']
  };

  const createFilter = async () => {
    try {
      const filterId = await provider.send('eth_newFilter', [filter]);
      console.log(filterId); // the filter ID returned by eth_newFilter
      return filterId
    } catch (error) {
      console.log(error);
    }
  };

  createFilter();
  ```

  ```python web3.py theme={"system"}
  from web3 import Web3  
  node_url = "CHAINSTACK_NODE_URL" 
  web3 = Web3(Web3.HTTPProvider(node_url))

  filter = {
      'toBlock': 'latest',
      'address': '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
      'topics': ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef']
  }

  def create_logs_filter(filter_object):
      try:
          logs_filter = web3.eth.filter(filter_object)
          return logs_filter
      except Exception as e:
          print(e)

  logs_filter = create_logs_filter(filter)
  filter_id = logs_filter.filter_id
  print(f'New filter ID: {filter_id}')
  ```
</CodeGroup>

## Use case

You can use `eth_newFilter` to create a filter for a specific action on a smart contract, for example, to monitor the transfer transactions from the [Wrapped ETH token](https://polygonscan.com/token/0x7ceb23fd6bc0add59e62ac25578270cff1b9f619).

The idea is to create a filter using the `eth_newFilter` method to monitor an ERC-20 smart contract, WETH in this case.

The following filter parameters are selected:

```javascript filter_params theme={"system"}
const filter = {
  // Poll the latest block available
  toBlock: 'latest',	
  
  // WETH smart contract address
  address: '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619',
  
  // Signature of the Transfer event.
  topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'], 
};
```

The program is then polling the filter every 2 seconds to check for any new changes using the `eth_getFilterChanges` method.

Here is the implementation using ethers.js:

```javascript index.js theme={"system"}
const ethers = require('ethers');
const NODE_URL = "CHAINSTACK_NODE_URL";
const provider = new ethers.providers.JsonRpcProvider(NODE_URL);

const filter = {
  toBlock: 'latest',
  address: '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619',
  topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'],
};

const createAndPollFilter = async () => {
  try {
    const filterId = await provider.send('eth_newFilter', [filter]);
    console.log(`The filter ID is: ${filterId}`); // the filter ID returned by eth_newFilter

    // Poll the filter every 30 seconds
    setInterval(async () => {
      const filterChanges = await provider.send('eth_getFilterChanges', [filterId]);

      if (filterChanges.length === 0) {
        console.log('No new logs since the last poll.');
      } else {
        console.log(filterChanges); // the filter changes returned by eth_getFilterChanges
      }
    }, 2000); // 2 seconds in milliseconds

    return filterId;
  } catch (error) {
    console.log(error);
  }
};

createAndPollFilter();
```

Here's a breakdown of how the code works:

The `createAndPollFilter` function is an asynchronous function that creates and polls a filter for the WETH smart contract on Polygon.

The `eth_newFilter` method creates a new filter with the specified parameters. In this case, it passes in the filter object as the filter parameter. The method returns the ID of the newly created filter, which is then logged into the console.

The `setInterval` method is used to poll the filter every 2 seconds. It takes a function as the first argument and an interval in milliseconds as the second argument. The function passed to `setInterval` is an asynchronous function that calls `eth_getFilterChanges` with the filter ID returned by `eth_newFilter`. This method returns an array of all the changes to the filter since the last time it was polled. If there are no changes, it logs "No new logs since the last poll." to the console. If there are changes, it logs the filter changes to the console.

The `createAndPollFilter` function returns the filter ID, and if there are any errors thrown while creating or polling the filter, the catch block logs the error to the console.


## OpenAPI

````yaml openapi/polygon_node_api/logs_and_events/eth_newFilter.json POST /a9bca2f0f84b54086ceebe590316fff3
openapi: 3.0.0
info:
  title: eth_newFilter example
  version: 1.0.0
  description: This is an API exampke for eth_newFilter.
servers:
  - url: https://nd-828-700-214.p2pify.com
security: []
paths:
  /a9bca2f0f84b54086ceebe590316fff3:
    post:
      tags:
        - upload
      summary: eth_newFilter
      operationId: newFilter
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                method:
                  type: string
                  default: eth_newFilter
                params:
                  type: array
                  items:
                    type: object
                    properties:
                      fromBlock:
                        type: string
                        default: latest
                      address:
                        type: string
                        default: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
                      topics:
                        type: array
                        items:
                          type: string
                          default: >-
                            0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
                  default:
                    - fromBlock: latest
                      address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
                      topics:
                        - >-
                          0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
      responses:
        '200':
          description: The filter ID
          content:
            application/json:
              schema:
                type: object
                properties:
                  jsonrpc:
                    type: string
                  id:
                    type: integer
                  result:
                    type: string

````