Search code examples
blockchainethereum

How to listen to Transfers events/logs of ETH (native token)


I'm using ethers.js and Infura, to listen ERC-20 Transfers events of USDT etc. From what I saw, I need to get the trx of each block to get the Transfers of ETH.

const { ethers, Contract } = require("ethers");

const { addEvent } = require('./events');
const tokens = require('./contracts/tokenConfigs.json');

const provider = new ethers.providers.JsonRpcProvider(`xxx`);

const main = async ({
    name,
    symbol,
    address,
    eventType,
    threshold,
    decimals,
    blockExplorerUrl,
    ABIpath,
}) => {
    const ERC20_ABI = require(ABIpath);
    const contract = new Contract(address, ERC20_ABI, provider);

    contract.on('Transfer', async (from, to, amount, data) => {
        if (amount.toNumber() >= threshold) {
            console.log(`Whale transfer alert for ${name} ${blockExplorerUrl}${data.transactionHash}`);

            await addEvent({...});
        }
    });
}

Solution

  • Native token transfers generally don't emit event logs, unless the transfer is part of an EVM message call (aka internal transaction) and the event is explicitly specified in the contract code.

    event Transferred(address indexed recipient, uint256 amount);
    
    function transferETH(address payable recipient) external payable {
        recipient.transfer(msg.value);
        emit Transferred(recipient, msg.value);
    }
    

    If you want to get native transfers of an address, you'll need to use an existing aggregated database or build one yourself by looping through all transaction receipts in all blocks. Note that internal transactions are not available in the receipts and you'll need to reconstruct them - for example using the debug_traceTransaction method.