Watch Token Transfers
token.watchTransfer
Watches TIP-20 Transfer events for a token.
Usage
import { } from './viem.config'
const = ..({
: '0x20c0000000000000000000000000000000000000',
})
.(() => {
for (const of ) .(.)
{ from: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', amount: 100000000n}
})
// Later, tear down the watcher.
.()import { , } from 'viem/tempo'
export const = .({
: .('0x...'),
})Also callable standalone: Actions.token.watchTransfer(client, options), with Actions imported from 'viem/tempo'.
Recipes
Credit Customer Deposits as They Arrive
Filter args.to to a deposit address to credit customer accounts on incoming transfers, formatting amounts for the ledger with Value.format.
import { } from 'viem/utils'
import { } from './viem.config'
const = ..({
: { : '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb' },
: '0x20c0000000000000000000000000000000000000',
})
.(() => {
for (const of ) {
// Credit the customer account mapped to this deposit address.
.('Deposit:', .., .(.., 6))
Deposit: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 249.99
}
})import { , } from 'viem/tempo'
export const = .({
: .('0x...'),
})Sync an Offchain Ledger From a Checkpoint
Pass fromBlock when a ledger service restarts: transfers missed while it was offline replay first, then live events follow on the same stream.
import { } from './viem.config'
// Last block the ledger recorded, loaded from its store.
const = 1_204_320n
const = ..({
: + 1n,
: '0x20c0000000000000000000000000000000000000',
})
for await (const { } of ) {
for (const of ) {
// Record the transfer, then advance the checkpoint.
.(., .., .., ..)
}
}import { , } from 'viem/tempo'
export const = .({
: .('0x...'),
})Return Value
Returns a watcher handle. Watching starts when the first listener (or async iterator) attaches, and stops when off is called.
type ReturnType = {
/** Registers a log listener. Starts the watcher on first registration. Returns an unregister function. */
onLogs: (fn: (logs: readonly Log[]) => void) => () => void
/** Registers an error listener. Returns an unregister function. */
onError: (fn: (error: Error) => void) => () => void
/** Tears down the watcher: removes listeners, ends iterators, stops the poll or subscription. */
off: () => void
/** Async-iterates emitted log batches (latest-only stream). */
[Symbol.asyncIterator]: () => AsyncIterableIterator<{ logs: readonly Log[] }>
}Each log is decoded, with the event arguments on args:
type Log = {
/** Decoded `Transfer` event arguments. */
args: {
/** Address that sent the tokens. */
from: Address
/** Address that received the tokens. */
to: Address
/** Amount transferred. */
amount: bigint
}
/** Name of the emitted event. */
eventName: 'Transfer'
// ...standard log fields (address, blockHash, blockNumber, logIndex, transactionHash, ...)
}Parameters
args
- Type:
object
type Args = {
/** Filter by sender address. */
from?: Address | Address[] | null
/** Filter by recipient address. */
to?: Address | Address[] | null
}Indexed argument values to filter logs by.
batch
- Type:
boolean - Default:
true
Whether to batch the logs found within a poll interval into a single emission. When false, each log is emitted on its own.
fromBlock
- Type:
bigint
Block number from which to start watching for logs.
poll
- Type:
boolean
Whether to poll for new logs instead of using a subscription. Defaults to true when the transport cannot subscribe or fromBlock is provided.
pollingInterval
- Type:
number - Default:
client.pollingInterval
Polling frequency (in ms).
token
- Type:
Address | bigint
Token to operate on: a TIP-20 token id or a contract address.