Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
1.3 kB
2
Indexable
Never
import { ethers } from "ethers";
import log from "../utils/logger";

export default class ETHListener {

    private readonly rpcUrl: string;
    private readonly ownWallet: string;
    private provider!: ethers.providers.WebSocketProvider;

    constructor(url: string, walletAddress: string) {
        this.rpcUrl = url;
        this.ownWallet = walletAddress;
    }

    initialize(): void {
        this.provider = new ethers.providers.WebSocketProvider(this.rpcUrl);
    }

    async startListening(fn: (data: any) => Promise<void>): Promise<void> {
        this.initialize();
        if (this.provider && await this.provider.ready) log.info("=> ETH Listener started");
        this.provider.on("block", async (block: number) => {
            log.info(`=> New Block: ${block}`);
            const blockData = await this.provider.getBlockWithTransactions(block);
            if (blockData && blockData.transactions.length > 0) {
                blockData.transactions.forEach(async (tx) => {
                    if (tx.to === this.ownWallet) {
                        await tx.wait()
                        return await fn(tx);
                    }
                });
            }
        });
    }

    public get getProvider(): ethers.providers.WebSocketProvider {
        return this.provider;
    }
};
Leave a Comment