How to Subscribe to Pending Transactions via WebSocket Endpoints

Learn how to subscribe to pending transactions via WebSockets, and filters the transactions based on specified from and/or to addresses.

In this tutorial, you’ll utilize the alchemy_pendingTransactions subscription type API endpoint. If you require the script or further details, refer to the following articles or continue reading for more.

docs.alchemy.comdocs.alchemy.com

alchemy_pendingTransactions

Alchemy provides the most effective method to subscribe to pending transactions, log events, and new blocks using WebSockets on Ethereum, Polygon, Arbitrum, and Optimism. By leveraging modern Web3 libraries, you’re able to access direct subscription types by simply connecting to each endpoint.

In this tutorial, we will test and create a sample project using the alchemy_pendingTransactions method offered by Alchemy’s WebSocket API.

What relevance does the alchemy_pendingTransactions provide to users?

  • Watching for pending transactions sent to a set of NFT owners to track the most recent floor price
  • Watching transactions sent from a whale trader to track trading patterns

How does alchemy_pendingTransactions compare to newPendingTransactions? Both these subscription types enable developers to receive transaction hashes that are sent to the network and marked as “pending”. However, alchemy_pendingTransactionsenhance the developer experience by providing filters that can specify based on to/from addresses. This greatly improves the readability of the transaction requests received.

It allows for strengthened requests with specific parameters given by the user including:

  • toAddress(optional): Singular address or array of addresses to receive pending transactions sent from this address.
  • fromAddress(optional): Singular address or array of addresses from receive pending transactions sent from this address.
  • hashesOnly(optional - default set to false): The response matches the payload of eth_getTransactionByHash. This is information about a transaction by the transaction hash including blockHash, blockNumber and transactionIndex.

Step 0: Configure your developer environment

Before you begin, complete the following steps to set up your web3 developer environment.

1. Install Node.js (> 14) on your local machine

2. Install npm on your local machine

3. Install wscat on your local machine

To check your Node version, run the following command in your terminal:

bash
$node -v

4. Create a free Alchemy account

Step 1: Open your Alchemy App

Once your Alchemy account is created, there will also be a default app that is also created.

To create another Alchemy app, check out this video.

Step 2: Get WebSocket URL from Alchemy App

Once you have created your app, get your WebSocket URL that we will use later in this tutorial.

  1. Click on your app’s View Key button in the dashboard
  2. Copy and save the WebSocket URL

Step 3: Output Pending Transactions Using wscat

Wscat is a terminal or shell tool used to connect to the WebSockets server. Each Alchemy application will provide a WebSocket URL that can be used directly with the wscat command.

  1. Initiate the WebSocket stream
  2. Enter the specific call command

From your terminal, run the following commands:

wscat
$// initiate websocket stream first
>wscat -c wss://eth-mainnet.g.alchemy.com/v2/demo
>
>// then call subscription
>{"jsonrpc":"2.0","id": 2, "method": "eth_subscribe", "params": ["alchemy_pendingTransactions", {"toAddress": ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "0xdAC17F958D2ee523a2206206994597C13D831ec7"], "hashesOnly": false}]}

If successful, you should see output that looks something like this:

Results
1{"id":1,"result":"0xf13f7073ddef66a8c1b0c9c9f0e543c3","jsonrpc":"2.0"}
2
3{
4 "jsonrpc": "2.0",
5 "method": "eth_subscription",
6 "params": {
7 "result": {
8 "blockHash": null,
9 "blockNumber": null,
10 "from": "0x098bdcdc84ab11a57b7c156557dca8cef853523d",
11 "gas": "0x1284a",
12 "gasPrice": "0x6fc23ac00",
13 "hash": "0x10466101bd8979f3dcba18eb72155be87bdcd4962527d97c84ad93fc4ad5d461",
14 "input": "0xa9059cbb00000000000000000000000054406f1ec84f89532f83768f3f159b73b237257f0000000000000000000000000000000000000000000000000000000001c9c380",
15 "nonce": "0x11",
16 "to": "0xdac17f958d2ee523a2206206994597c13d831ec7",
17 "transactionIndex": null,
18 "value": "0x0",
19 "type": "0x0",
20 "v": "0x26",
21 "r": "0x93ddd646056f365352f7e53dfe5dc81bde53f5b7c7bbe5deea555a62540d6995",
22 "s": "0x79ed82a681930feb11eb68feccd1df2e53e1b96cf9171ae4ffcf53e9b2a40e8e"
23 },
24 "subscription": "0xf13f7073ddef66a8c1b0c9c9f0e543c3"
25 }
26}

By using wscat, you are able to verify the transaction immediately via the computer’s terminal or shell.

Step 4: Create a Node project

Let’s create an empty repository and install the necessary dependencies for WebSocket connections. We can use either Viem or Ethers.js to manage WebSocket subscriptions.

From your terminal, run the following commands:

$mkdir pending-transactions && cd pending-transactions
>npm init -y
>npm install viem
>touch main.js

This will create a repository named pending-transactions that holds all the files and dependencies we need.

Open this repo in your preferred code editor, where we’ll write our code in the main.js file.

Step 5: Output Pending Transactions using WebSocket libraries

Next, we’ll demonstrate how to use Viem or Ethers.js to create an alchemy_pendingTransactions subscription.

To make requests using Alchemy’s pendingTransactions API, we recommend reviewing the alchemy_pendingTransactions docs.

Next, add the following code to the main.js file, using your Alchemy API key:

1import { createPublicClient, webSocket } from 'viem'
2import { mainnet } from 'viem/chains'
3
4const client = createPublicClient({
5 chain: mainnet,
6 transport: webSocket('wss://eth-mainnet.g.alchemy.com/v2/<-- ALCHEMY APP API KEY -->')
7})
8
9// Subscribe to pending transactions
10const unsubscribe = client.watchPendingTransactions({
11 onTransactions: (hashes) => {
12 console.log('Pending transaction hashes:', hashes)
13 // To get full transaction details, you can fetch each hash:
14 // hashes.forEach(async (hash) => {
15 // const tx = await client.getTransaction({ hash })
16 // console.log(tx)
17 // })
18 }
19})
20
21console.log('Listening for pending transactions...')

Run this script by running the following command in your terminal:

node main.js

If successful, you should see a stream of transactions as the result. This stream of output indicates the latest (pending or mined) transactions hitting the Ethereum Mainnet. It should look something like this:

Results
1{
2 blockHash: null,
3 blockNumber: null,
4 from: '0x0dd25571522e0ac38712b56834dc6081cde33325',
5 gas: '0x8b5d7',
6 gasPrice: '0xd09dc30c',
7 hash: '0x9575c90c4923d7d1981029bfcfc3f23b91ec78683b881b571763dff0c00a72da',
8 input: '0x0357371d0000000000000000000000000dd25571522e0ac38712b56834dc6081cde3332500000000000000000000000000000000000000000000000000b1a2bc2ec50000',
9 nonce: '0x14c',
10 to: '0xfebfd3467c4362eee971c433e3613c009ab55ce4',
11 transactionIndex: null,
12 value: '0x0',
13 type: '0x0',
14 v: '0x27125',
15 r: '0xdc427da8df7cd9a4e831734a9ec4d8127d2c068497e667138b0092635157c5db',
16 s: '0x5d4b996fd467702e7602030de3517e024a31085d57cfe2ff064e98460bc2da28'
17}
18{
19 blockHash: null,
20 blockNumber: null,
21 from: '0x61141bce5352fc9b5ff648468676e356518d86ab',
22 gas: '0x55730',
23 gasPrice: '0x77359410',
24 hash: '0xc81a148daba8bb67daca8b3e645d07c9caaf2977ebdd46245f97f12cc3737dd2',
25 input: '0x29dd214d00000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000005000000000000000000000000af28cb0d9e045170e1642321b964740784e7dc640000000000000000000000000000000000000000000000000ddf17ab47bc33b40000000000000000000000000000000000000000000000000000000000000100ee569c3895715793e17640229cd2462886335a0940e299921bb2eef69618bb730000000000000000000000000000000000000000000000000000000000000014805fe47d1fe7d86496753bb4b36206953c1ae660000000000000000000000000000000000000000000000000000000000000000000000000000000000000016065f49bd49de252a7f0d9100776c70f0da398368ef9866f8e21fbb0e3e630e74f00000000000000000000000090294dca1861b78d8aaa4acd1abf4c9b535c490e000000000000000000000000cc7bb2d219a0fc08033e130629c2b854b7ba919500000000000000000000000000000000000000000000000029a2241af62c00000000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000080383847bd75f91c168269aa74004877592f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001490294dca1861b78d8aaa4acd1abf4c9b535c490e000000000000000000000000',
26 nonce: '0x3f927',
27 to: '0x000054d3a0bc83ec7808f52fcdc28a96c89f6c5c',
28 transactionIndex: null,
29 value: '0x0',
30 type: '0x0',
31 v: '0x27125',
32 r: '0x5466a7a7d1823c2290fc4803cac0340dcab34e843a8c0681763ca60fd7ccc7b2',
33 s: '0x3030ce868c4d09b71009af597175bdecace2f081a0f78f0e4705e318d19076a9'
34}
35....

Step 6: Filter Pending Transactions

Next, we’ll demonstrate how to filter pending transactions based on addresses. While standard WebSocket subscriptions don’t offer built-in filtering, we can implement filtering logic in our application.

Note: The Alchemy-enhanced alchemy_pendingTransactions API provides native filtering by fromAddress and toAddress. For standard WebSocket subscriptions, we need to implement filtering manually as shown below.

Add the following code to the main.js file, using your Alchemy API key:

1import { createPublicClient, webSocket } from 'viem'
2import { mainnet } from 'viem/chains'
3
4const client = createPublicClient({
5 chain: mainnet,
6 transport: webSocket('wss://eth-mainnet.g.alchemy.com/v2/<-- ALCHEMY APP API KEY -->')
7})
8
9// Addresses to filter for
10const fromAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
11const toAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
12
13// Subscribe to pending transactions with filtering
14const unsubscribe = client.watchPendingTransactions({
15 onTransactions: async (hashes) => {
16 for (const hash of hashes) {
17 try {
18 const tx = await client.getTransaction({ hash })
19
20 // Filter transactions by from/to address
21 if (tx.from?.toLowerCase() === fromAddress.toLowerCase() ||
22 tx.to?.toLowerCase() === toAddress.toLowerCase()) {
23 console.log('Filtered pending transaction:', tx)
24 }
25 } catch (error) {
26 // Skip transactions that can't be fetched
27 continue
28 }
29 }
30 }
31})
32
33console.log(`Listening for pending transactions from ${fromAddress} or to ${toAddress}...`)

Conclusion

You now know how to use WebSocket connections with Viem and Ethers.js to subscribe to pending transactions and filter them based on addresses.

For more advanced filtering capabilities, consider using Alchemy’s enhanced alchemy_pendingTransactions API which provides native filtering by fromAddress and toAddress.

If you enjoyed this tutorial, tweet us at @Alchemy.

If you have any questions or feedback, please contact us at [email protected] or open a ticket in the dashboard.