> ## Documentation Index
> Fetch the complete documentation index at: https://chainstack-docs-polygon-erigon-trace-deprecation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# subscribe ("pendingTransactions") | Ethereum

> Reference docs for the subscribe ("pendingTransactions") JSON-RPC method on the Ethereum blockchain, available via Chainstack JSON-RPC nodes.

The ethers.js subscription equivalent to [eth\_newPendingTransactionFilter](/reference/ethereum-newpendingtransactionfilter). `subscribe("pendingTransactions")` allows developers to subscribe to real-time updates about pending transactions on the Ethereum blockchain; the application will receive notifications whenever a pending transaction appears on the blockchain.

If you are using this method to track your own transactions, make sure [MEV protection](/docs/mev-protection) is disabled. Otherwise you won't detect them as they go through a private pool.

## Parameters

* `string` — the event name to subscribe to, `"pending"` in ethers.js, which maps to the `pendingTransactions` subscription.
* `function` — a listener function that is called every time a new pending transaction is received. In ethers.js this listener receives a single parameter, the transaction hash.

## Response

* `string` — the hash identifying the pending transaction.

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

<Info>
  Note that ethers.js subscriptions require a WebSocket connection, so use `ethers.WebSocketProvider`.
</Info>

Use the provider event API to attach listeners and manage the subscription:

* `provider.on("pending", listener)` — registers a listener that runs for each new pending transaction and receives the transaction hash.
* `listener` — your callback handles any errors internally, so wrap the work in a `try...catch` block.
* `provider.off("pending", listener)` — removes the listener to stop receiving pending transactions.
* `provider.destroy()` — closes the WebSocket connection when you are done.

<CodeGroup>
  ```javascript index.js theme={null}
  const { ethers } = require("ethers");

  const NODE_URL = "CHAINSTACK_WSS_URL"; // Ensure this is your WebSocket endpoint
  const provider = new ethers.WebSocketProvider(NODE_URL);

  async function subscribeToPendingTransactions() {
    try {
      // Subscribe to pending transactions
      await provider.on('pending', (transactionHash) => {
        // Listener for new pending transactions
        console.log('New pending transaction:', transactionHash);
      });

      console.log('Subscription successful');
    } catch (error) {
      console.error(`Error subscribing to pending transactions: ${error}`);
    }
  }

  subscribeToPendingTransactions();
  ```
</CodeGroup>

## Use case

A practical use case for `subscribe("pendingTransactions")` is a DApp that continuously listens for new pending transactions, then isolates the `from`, `to`, and `value` fields for analytics purposes. This is useful, for example, to only track transactions that move at least a certain amount of ETH.

The following is an implementation of this concept using ethers.js subscriptions:

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

  async function subscribeToPendingTransactions() {
    try {
        // Listener for new pending transactions
        await provider.on('pending', handleNewPending);

        console.log("Subscription successful");
    } catch (error) {
        console.error(`Error subscribing to pending transactions: ${error}`);
    }
  }

  // Adapted to be able to call unsubscribe correctly
  async function unsubscribe() {
    try {
        await provider.off('pending', handleNewPending);
        await provider.destroy();
        console.log("Successfully unsubscribed!");
        process.exit(0); // Exiting normally
    } catch (error) {
        console.error(`Error unsubscribing: ${error}`);
        process.exit(1); // Exiting with an error
    }
  }

  // Listener that logs the received pending transactions and extracts from, to, and value fields
  async function handleNewPending(transactionHash) {
    try {
        const transaction = await provider.getTransaction(transactionHash);
        const from = transaction.from;
        const to = transaction.to;
        const value = transaction.value;
        if (value >= 1000000000000000000n) { // 1 ETH in wei
            console.log(`----- New pending transaction ------`);
            console.log(`From: ${from}`)
            console.log(`To: ${to}`)
            console.log(`Value: ${Number(ethers.formatEther(value)).toFixed(2)} ETH \n`)

        }

    } catch (error) {
        console.error(`Error getting transaction: ${error}`);
    }
  }

  subscribeToPendingTransactions();
  ```
</CodeGroup>

This code creates a new subscription to pending transactions using the `provider.on("pending", listener)` method on a `WebSocketProvider`. This registers a listener that runs for every new pending transaction hash.

The code defines the `handleNewPending` listener function that is attached to the provider. The `handleNewPending` function is called when a new pending transaction is received; it runs the [eth\_getTransactionByHash](/reference/ethereum-gettransactionbyhash) method and extracts the `from`, `to`, and `value` fields. If the value transferred is above 1 ETH, the data is logged.

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

Finally, the code calls the `subscribeToPendingTransactions` function, which creates the subscription and attaches the listener. When a new pending transaction is received, the `handleNewPending` function is called to extract the data and log it to the console.
