watchPendingTransactions
Watches and returns pending transaction hashes.
This Action will batch up all the pending transactions found within the pollingInterval
, and invoke them via onTransactions
.
Usage
ts
import { publicClient } from './client'
const unwatch = publicClient.watchPendingTransactions(
{ onTransactions: hashes => console.log(hashes) }
)
/**
* > ['0x...', '0x...', '0x...']
* > ['0x...', '0x...']
* > ['0x...', '0x...', '0x...', ...]
*/
ts
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
export const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
Returns
UnwatchFn
A function that can be invoked to stop watching for new pending transaction hashes.
Parameters
onTransactions
- Type:
(hashes: '0x${string}'[]) => void
The new pending transaction hashes.
ts
const unwatch = publicClient.watchPendingTransactions(
{ onTransactions: hashes => console.log(hashes) }
)
batch (optional)
- Type:
boolean
- Default:
true
Whether or not to batch the transaction hashes between polling intervals.
ts
const unwatch = publicClient.watchPendingTransactions(
{
batch: false,
onTransactions: hashes => console.log(hashes),
}
)
onError (optional)
- Type:
(error: Error) => void
Error thrown from listening for new pending transactions.
ts
const unwatch = publicClient.watchPendingTransactions(
{
onError: error => console.log(error)
onTransactions: hashes => console.log(hashes),
}
)
poll (optional)
- Type:
boolean
- Default:
false
for WebSocket Clients,true
for non-WebSocket Clients
Whether or not to use a polling mechanism to check for new pending transactions instead of a WebSocket subscription.
This option is only configurable for Clients with a WebSocket Transport.
ts
import { createPublicClient, webSocket } from 'viem'
import { mainnet } from 'viem/chains'
const publicClient = createPublicClient({
chain: mainnet,
transport: webSocket()
})
const unwatch = publicClient.watchPendingTransactions(
{
onTransactions: transactions => console.log(transactions),
poll: true,
}
)
pollingInterval (optional)
- Type:
number
Polling frequency (in ms). Defaults to the Client's pollingInterval
config.
ts
const unwatch = publicClient..watchPendingTransactions(
{
pollingInterval: 1_000,
onTransactions: hashes => console.log(hashes),
}
)
JSON-RPC Methods
- When
poll: true
- Calls
eth_newPendingTransactionFilter
to initialize the filter. - Calls
eth_getFilterChanges
on a polling interval.
- Calls
- When
poll: false
& WebSocket Transport, uses a WebSocket subscription viaeth_subscribe
and the"newPendingTransactions"
event.