Detail of blockchain monitors

Overview

This document provides a detailed explanation of how a blockchain listener based on ethers.js works, covering key concepts such as event triggers, data processing, and performance optimization.

How the Listener Works

1. Event Trigger Mechanism

provider.on("block", sharedNativeListener);

This line of code registers a "block" event listener. The workflow is as follows:

  1. A new block is generated on the blockchain → Contains multiple transactions.

  2. WebSocket push notification → ethers.js receives the new block event.

  3. Automatic invocation of the listenersharedNativeListener(blockNumber) is called.

2. Detailed Analysis of the Listener Function

sharedNativeListener = async (blockNumber: number) => {
    // Step 1: Fetch the full block data (including all transactions)
    const block = await provider.getBlockWithTransactions(blockNumber);

    // Step 2: Iterate through each transaction in the block
    for (const tx of block.transactions) {
        // Step 3: Check if the transaction has a recipient address
        if (tx.to) {
            const toAddr = tx.to.toLowerCase();

            // Step 4: Check if the recipient address is in our watch list
            if (subscribedWallets.has(toAddr)) {
                // Step 5: If it matches, log the transfer information
                console.log(`💰 Wallet ${toAddr} received BNB...`);
            }
        }
    }
};

Data Flow Explanation

Example of Block Structure

Listener's Processing Flow

Hierarchical Structure of the Listener Mechanism

Layer 1: Blockchain Network

Layer 2: WebSocket Connection

Layer 3: ethers.js Provider

Layer 4: Your Listener

Why Is This Design Efficient?

1. Batch Processing

2. Precise Filtering

3. Real-Time

Listener Lifecycle

Data Flow Diagram

Core Code Examples

Event Registration

Fetching Block Data

Address Match Check

Performance Optimization Tips

  1. Use a Map structure: subscribedWallets is implemented using Map for O(1) lookup.

  2. Batch Processing: Process once per block, not per transaction.

  3. Early Exit: Skip unmatched transactions immediately.

  4. Shared Listener: Multiple addresses share the same listener.

Error Handling Recommendations

Conclusion

The core idea of this listener is:

  1. Listen to blocks rather than individual transactions.

  2. Batch check all transactions within a block.

  3. Filter matches by only processing transactions sent to target addresses.

  4. Respond in real-time when new blocks are generated.

This mechanism ensures both real-time responsiveness and avoids excessive network requests, making it a classic model for blockchain listening.

Extended Applications

  • Exchange Deposit Listening: Monitor user deposit addresses.

  • DeFi Protocol Monitoring: Track smart contract events.

  • Wallet Applications: Real-time balance changes.

  • Analysis Tools: Track on-chain data activity.

Last updated