How to Monitor USDT / USDC Payments with Webhooks and RPC
Build a payment receiver and polling cursor. Verify token contracts, recipients and integer amounts, deduplicate events and reconcile missing or replaced blocks.
For stablecoin payment monitoring or exchange deposit detection, monitor incoming ERC-20 USDT / USDC transfers on EVM chains using Webhooks, WebSocket logs or HTTP polling. Developers and AI agents use the same APIs; select the chain, token contract, recipient and confirmation depth before processing payments. Choose a deposit, merchant-notification or payout workflow in the USDT / USDC transfer monitoring solution.
- First step: Create a subscription and watch the recipient, starting with an API key and your HTTPS receiver.
- Done when: A matching transfer passes signature, chain, token, recipient and integer-amount checks, is stored once as a payment candidate, and the receiver returns HTTP
204; verify it on-chain under your confirmation policy before crediting it.
Basic transfer monitoring is available. Amount and token filtering runs in your receiver. Server-side conditions, multiple confirmation stages and IM alerts are coming soon.
For developers and AI Agents: start with an API key and your own HTTPS receiver; filter token contracts and amounts in your application. Copy the webhook setup.
Tasks this guide helps you complete
- Receive USDT / USDC payment notifications at your HTTPS endpoint after checking Push support for the selected chain.
- Validate a transfer candidate by checking its chain, token contract, recipient and integer amount before applying your on-chain verification and confirmation policy.
- Backfill missing transfer logs with bounded
eth_getLogsqueries and a saved cursor.
Choose Webhook, WebSocket or polling
| Method | Use it for | Recovery |
|---|---|---|
| Webhook | Address activity sent to your HTTPS receiver, including incoming token transfers | Verify signatures, deduplicate event IDs and handle subscription.gap / chain.reorg; replay retained matches |
| WebSocket | Filtered logs over a persistent connection | Reconnect, re-subscribe and backfill missed blocks |
| HTTP polling | Scheduled monitoring or historical log backfill with your own cursor | Query bounded eth_getLogs ranges and persist progress |
Read ws and subscriptions in the public GET /v1/chains response before choosing WebSocket. Push support is a separate check: read GET /v1/push/chains with your API key. A chain without WebSocket can use address Webhooks if it is listed there. Use polling when you need to scan earlier blocks or run without a persistent connection.
Receive payments with Webhooks
Create a subscription and watch the recipient
Get an API key and deploy an HTTPS receiver on port 443. Select CHAIN from the authenticated Push chain list, set RECIPIENT to your deposit address and RECEIVER_URL to your receiver URL. This shell example requires jq; {} uses the chain's default confirmation count. Inspect min_confirmations, default_confirmations and max_confirmations before choosing a different count. The Push OpenAPI defines these requests.
set -eu
umask 077
: "${BLOCKVECTRA_API_KEY:?Set your API key}"
: "${CHAIN:?Select a chain from the Push chain list}"
: "${RECIPIENT:?Set the watched EVM recipient address}"
: "${RECEIVER_URL:?Set your HTTPS receiver URL}"
PUSH_URL='https://api.blockvectra.com/v1/push'
curl --fail-with-body -sS "$PUSH_URL/chains" \
-H "x-api-key: $BLOCKVECTRA_API_KEY" > push-chains.json
jq -e --arg chain "$CHAIN" 'any(.chains[]; .chain == $chain)' push-chains.json
jq -n --arg url "$RECEIVER_URL" --arg chain "$CHAIN" \
'{url: $url, chains: {($chain): {}}}' > create.json
curl --fail-with-body -sS "$PUSH_URL/subscriptions" \
-H "x-api-key: $BLOCKVECTRA_API_KEY" \
-H 'Content-Type: application/json' -d @create.json > subscription.json
SUBSCRIPTION_ID=$(jq -er '.id' subscription.json)
jq -n --arg recipient "$RECIPIENT" '{addresses: [$recipient]}' > addresses.json
curl --fail-with-body -sS "$PUSH_URL/subscriptions/$SUBSCRIPTION_ID/addresses/add" \
-H "x-api-key: $BLOCKVECTRA_API_KEY" \
-H 'Content-Type: application/json' -d @addresses.json > address-change.json
curl --fail-with-body -sS "$PUSH_URL/subscriptions/$SUBSCRIPTION_ID" \
-H "x-api-key: $BLOCKVECTRA_API_KEY"Creation returns id and secret. Store the secret securely for the receiver; subscription.json contains a credential. Poll the subscription until applied_version >= change_version from address-change.json, then record chains[CHAIN].applied_from_block. New addresses match from that block, so keep polling for any earlier payment interval.
Verify, deduplicate and validate payments
Save the raw-body signature function as verify-push.js. The receiver below accepts a Web API Request in Node.js and reads its original bytes before JSON parsing. Build secrets as a Map of subscription ID strings to stored secrets. Set trusted expected configuration to { chain, token, recipient, amountUnits }: token is the verified stablecoin contract on that chain and amountUnits is the expected positive integer amount in its smallest units. Compare amounts with BigInt, never floating-point numbers or the token symbol.
import { verifyPush } from './verify-push.js';
export function selectPayment(data, event, expected) {
if (data.chain !== expected.chain || event.type !== 'token.transfer' ||
event.standard !== 'erc20') return null;
const address = value => typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/.test(value);
if (![event.token, event.to, expected.token, expected.recipient].every(address)) return null;
if (event.token.toLowerCase() !== expected.token.toLowerCase() ||
event.to.toLowerCase() !== expected.recipient.toLowerCase()) return null;
const integer = value => typeof value === 'string' && /^[1-9][0-9]{0,77}$/.test(value);
if (!integer(event.amount) || !integer(expected.amountUnits)) return null;
const amount = BigInt(event.amount);
if (amount >= (1n << 256n) || amount !== BigInt(expected.amountUnits)) return null;
if (typeof event.id !== 'string' || typeof event.ref !== 'string' ||
!/^0x[0-9a-f]{64}$/.test(event.tx_hash) ||
!/^0x[0-9a-f]{64}$/.test(event.block_hash) ||
!Number.isSafeInteger(event.log_index) || event.log_index < 0 ||
!Number.isSafeInteger(event.block_number) || event.block_number < 0) return null;
return {
eventId: event.id, ref: event.ref, chain: data.chain,
token: event.token, recipient: event.to, amountUnits: event.amount,
txHash: event.tx_hash, logIndex: event.log_index,
blockHash: event.block_hash, blockNumber: event.block_number,
};
}
export async function receivePayments(request, expected, secrets, store) {
const rawBody = Buffer.from(await request.arrayBuffer());
const headers = Object.fromEntries(request.headers);
if (!verifyPush(rawBody, headers, secrets)) return new Response(null, { status: 401 });
let message;
try { message = JSON.parse(rawBody.toString('utf8')); }
catch { return new Response(null, { status: 400 }); }
const data = message?.data;
if (message?.type !== 'push.events' ||
!Number.isSafeInteger(data?.subscription_id) || data.subscription_id <= 0 ||
String(data.subscription_id) !== headers['bv-subscription-id'] ||
data.chain !== expected.chain || !Array.isArray(data.events)) {
return new Response(null, { status: 400 });
}
try {
await store.transaction(async tx => {
for (const event of data.events) {
if (!event || typeof event.id !== 'string') continue;
const recovery = event.type === 'subscription.gap' || event.type === 'chain.reorg';
const payment = selectPayment(data, event, expected);
if (!recovery && !payment) continue;
if (!await tx.insertEventOnce(data.subscription_id, event)) continue;
if (recovery) await tx.enqueueRecovery(data.chain, event);
else await tx.recordPaymentCandidate(payment);
}
});
} catch {
return new Response(null, { status: 503 });
}
return new Response(null, { status: 204 });
}Implement store.transaction with durable storage. Within one transaction, insertEventOnce inserts an event under a unique (subscription_id, event.id) key and returns false for a duplicate; commit it together with recordPaymentCandidate or enqueueRecovery. Roll back all writes on failure so a retry can process the event. Recovery jobs must also be idempotent. Return 2xx within 10 seconds only after committing; enforce the 1 MiB body limit in your HTTP server.
This example checks one expected payment amount. For multiple orders, look up trusted payment configuration by chain, token and recipient, and reconcile partial or excess payments under your own rules. A candidate still needs on-chain verification and your confirmation policy before crediting it. Across subscriptions and polling, reconcile the same transfer by chain, transaction hash and log index so two delivery paths do not credit it twice; retain the block hash to track replaced blocks.
Recover missing or replaced blocks
For subscription.gap, enqueue a scan of from_block through to_block using the polling path below or available Data API datasets. chain.reorg is a free notice that delivered blocks were replaced, not a delivery gap. Mark or discard old events in that range by ref; reconcile payment records by ref and tx_hash against the canonical chain before processing automatically redelivered canonical events with new IDs. Deduplicate those events by id. The reorg notice does not advance completed progress; record complete_through_block per chain, never infer completion from the largest event block number.
Replay accepts chain and from_block inside the current replayable_from_block boundary. It only resends retained matches; it does not scan periods before the address or chain was added, or periods when the subscription was offline. Keep a polling cursor to cover those intervals and expired gaps. Request failures and invalid replay ranges are covered in the error reference; delivery, history and address-day charges are explained in billing rules.
The remaining sections implement ERC-20 log filtering and cursor-based polling for monitoring and recovery.
Transfer Event and Filter Parameters
Standard ERC-20 token contracts emit the following event on every transfer:
event Transfer(address indexed from, address indexed to, uint256 value);When calling eth_getLogs, pass the token contract address and the topics array to filter matching logs:
| Parameter | Value | Description |
|---|---|---|
address | Token contract address (or array of addresses) | Target stablecoin contract address. You can specify a single address (e.g. BSC USDT 0x55d398326f99059fF775485246999027B3197955, Base USDC 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913), or an array of addresses to monitor multiple tokens concurrently |
topics[0] | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | Event signature hash: keccak256("Transfer(address,address,uint256)") |
topics[1] | null | Sender address (from). Because deposit monitoring accepts funds from any user wallet, pass null to match any sender |
topics[2] | 32-byte zero-padded recipient address | Destination address (to). Under EVM log specifications, indexed address parameters occupy 32 bytes (64 hex characters). Left-pad the 20-byte recipient address with 12 zero bytes (24 hexadecimal zero characters) to form a 32-byte topic. |
fromBlock | Starting block (hexadecimal) | Beginning of the query block range (inclusive) |
toBlock | Ending block (hexadecimal) | End of the query block range (inclusive) |
The unindexed value (transfer amount) is encoded in the log object's data field as a 32-byte hexadecimal uint256. Divide this raw amount by 10^decimals to get the human-readable token amount (e.g. 18 decimals for BSC USDT; 6 decimals for Base and Ethereum USDC).
Cursor Polling and Block Range Limits
A polling service queries new blocks at regular intervals (such as every 3 to 5 seconds).
Cursor Advancement
Maintain a persistent cursor last_polled_block (the highest block processed and committed) in your database:
- For each polling cycle, set
fromBlock = last_polled_block + 1. - Query the current chain head via
eth_blockNumber, and calculate the safe target heightsafe_headbased on your confirmation depth. - If
fromBlock <= safe_head, query logs in chunks up tosafe_head. After successfully processing each chunk, advance the cursor.
Block Range Limit
The block span of a single eth_getLogs call is calculated as toBlock − fromBlock + 1. It must not exceed the max_logs_block_range published for that chain in GET /v1/chains.
If a request exceeds this range, the service rejects the call with error code -32602:
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "eth_getLogs block range too large: max 1000 blocks",
"data": {
"reason": "logs_range_too_large",
"docs_url": "https://docs.blockvectra.com/en/errors/#logs_range_too_large",
"retryable": false
}
}
}Requests exceeding the block range return JSON-RPC error -32602 (not billed). In your application logic, read max_logs_block_range from GET /v1/chains and clamp each poll slice: chunk_end = min(fromBlock + max_logs_block_range - 1, safe_head).
Handling Block Reorganizations and Confirmation Depth
Near the tip of the blockchain, temporary block reorganizations (reorgs) can occur. Crediting payments at latest without confirmation depth risks crediting transactions on an orphaned branch that is subsequently discarded.
Apply the following safeguards to protect payment processing:
Confirmation Depth
Instead of querying up to latest, query up to a safe target block height:
safe_head = current_head - CONFIRMATION_DEPTH
Set CONFIRMATION_DEPTH according to your application's risk tolerance. Querying only up to safe_head ensures only blocks with sufficient confirmations are processed.
Reorganizations during Polling
Standard EVM JSON-RPC sets removed: true on log objects only in WebSocket logs subscription streams when a previously emitted event is reverted due to a chain reorg. When polling over HTTP with eth_getLogs, queries return logs from the canonical chain; reorged logs will simply not appear in subsequent queries. Polling within safe_head ensures payments are processed only on sufficiently confirmed blocks.
Deduplication by (transactionHash, logIndex)
Payment listeners must enforce strict idempotency:
- Multiple Transfers in One Transaction: A single transaction can contain multiple
Transferevents to the same deposit address (for example, token routers splitting swaps or multi-payout contracts). Important:transactionHashalone is not unique per payment. - Overlapping Polling & Retries: When polling services restart, recover from transient network errors, or rewind several blocks to handle shallow reorgs, logs from the same block range are queried multiple times.
- Log Index Uniqueness: The
logIndexidentifies the relative position of the event log within the block. Under EVM specifications, the canonical composite unique identifier for an event is(transactionHash, logIndex).
In relational database schemas, declare a composite unique index on your deposit records table:
CREATE UNIQUE INDEX idx_transfers_tx_log ON deposit_records (transaction_hash, log_index);Before processing a deposit, check against existing (transactionHash, logIndex) entries to guarantee that each on-chain transfer is credited exactly once.
Complete Code Examples
The examples below illustrate fetching network capabilities from /v1/chains, calculating safe block ranges, polling stablecoin Transfer logs in compliance with range limits, and deduplicating events.
import { createPublicClient, formatUnits, http, parseAbiItem } from "viem";
const apiKey = process.env.BLOCKVECTRA_API_KEY;
if (!apiKey) {
throw new Error("BLOCKVECTRA_API_KEY environment variable is not set");
}
const CHAIN = "bsc_mainnet";
const RPC_URL = "https://api.blockvectra.com/v1/bsc_mainnet";
const CHAINS_URL = "https://api.blockvectra.com/v1/chains";
// Target stablecoin contract address (BSC USDT used in this example)
const TOKEN_CONTRACT = "0x55d398326f99059fF775485246999027B3197955" as const;
const TOKEN_DECIMALS = 18;
// Monitored deposit address
const RECIPIENT_ADDRESS = "0xdded13D555B6DA811103cC1794D3d4330F69632C" as const;
// Confirmation depth to guard against chain reorgs
const CONFIRMATION_DEPTH = 15n;
// 1. Fetch chain capabilities from public metadata endpoint (unauthenticated, unbilled)
const chainsRes = await fetch(CHAINS_URL);
const { chains } = (await chainsRes.json()) as {
chains: Array<{
chain: string;
ws: boolean;
subscriptions: string[];
max_logs_block_range: number;
}>;
};
const chainConfig = chains.find((c) => c.chain === CHAIN);
if (!chainConfig) {
throw new Error(`Chain ${CHAIN} not found in /v1/chains`);
}
const maxLogsRange = BigInt(chainConfig.max_logs_block_range || 1000);
console.log(`Chain: ${CHAIN} | WebSocket supported: ${chainConfig.ws} | Max logs range: ${maxLogsRange}`);
// 2. Initialize viem client with x-api-key header
const client = createPublicClient({
transport: http(RPC_URL, {
fetchOptions: {
headers: { "x-api-key": apiKey },
},
}),
});
// Set to track processed events by composite key: (transactionHash, logIndex)
const processedLogs = new Set<string>();
// 3. Compute query range: subtract confirmation depth from current head
const currentHead = await client.getBlockNumber();
const safeHead = currentHead - CONFIRMATION_DEPTH;
// For demonstration, start cursor 10 blocks before safeHead
let cursor = safeHead > 10n ? safeHead - 10n : 0n;
console.log(`Current head: ${currentHead} | Safe head: ${safeHead} | Polling cursor: ${cursor}`);
while (cursor <= safeHead) {
const chunkEnd = cursor + maxLogsRange - 1n < safeHead ? cursor + maxLogsRange - 1n : safeHead;
const logs = await client.getLogs({
address: TOKEN_CONTRACT,
event: parseAbiItem(
"event Transfer(address indexed from, address indexed to, uint256 value)"
),
args: {
to: RECIPIENT_ADDRESS,
},
fromBlock: cursor,
toBlock: chunkEnd,
});
for (const log of logs) {
const dedupKey = `${log.transactionHash}-${log.logIndex}`;
if (processedLogs.has(dedupKey)) {
continue;
}
processedLogs.add(dedupKey);
const tokenAmount = formatUnits(log.args.value ?? 0n, TOKEN_DECIMALS);
console.log(
`[Payment Received] Amount: ${tokenAmount} | ` +
`Tx: ${log.transactionHash} | Log: ${log.logIndex} | Block: ${log.blockNumber}`
);
}
cursor = chunkEnd + 1n;
}
// Run with: npx tsx example.mtsBilling Rules and Related Guides
- For details on request metering, CU weights, and error code billing determinations, see Billing Rules: Errors and Non-Billed Requests.
- For in-depth guidance on
eth_getLogsblock range limits and chunking logic, see eth_getLogs Block Range Limits and Chunked Queries. - For differences between real-time RPC node queries and indexed historical transfer APIs, see Head-of-Chain vs Indexed History: When to Use eth_getLogs vs Transfers.
Next steps
- Browse the datasets directory to see every dataset BlockVectra indexes.
- See the free plan and pricing to check what your account includes.
- Log in to the console to create an API key.
Last updated:
Programmatic sign-up
Sign a message locally with your wallet and get an API key plus 30,000,000 free CU, no payment first. 3 BlockVectra HTTP requests and a local wallet signature in 4 steps, no browser, for developers and AI agents.
Verify Agent Payments
Run a read-only Node.js script that checks one direct Priors LineKey spend receipt on Robinhood Chain mainnet against your invoice: pinned contracts, Paid, Borrowed and USDG Transfer logs, exact integer amounts.