3

How can I get an Ethereum transaction hash whenever a particular NFT/ERC20 token is transferred? Not sure exactly what process/code is needed to do that.

2 Answers 2

2

You could use a WebSocket from a node provider to track the transfer event that all ERC-20 and ERC-721/1155 smart contracts emit when there is a token transfer.

Check this example in ethers v6:

const ethers = require("ethers");
const ABI = require("./abi.json"); //ABI of the smart contract
require("dotenv").config();

async function getTransfer(){
    const usdcAddress = "SMART_CONTRACT_ADDRESS"; 
    const provider = new ethers.WebSocketProvider(`WEBSOCKET_URL`);

    const contract = new ethers.Contract(usdcAddress, ABI, provider);

    contract.on("Transfer", (from, to, value, event)=>{

        let transferEvent ={
            from: from,
            to: to,
            value: value,
            eventData: event,
        }

        console.log(JSON.stringify(transferEvent, null, 4))

    })
}

getTransfer()

But with this, you'll have to manage filters for each token, and if you miss a filter change, it's gone.

Another way to track this is by using QuickAlerts, an on-chain alerting tool; you can set up an alert whenever a token is transferred. QuickAlerts not just makes event tracking easier but also has retry logic built-in so if you miss an alert it'll retry to send that alert multiple times.

A QuickAlerts expression to track token transfers would look like this:

(tx_logs_address == 'SMART_CONTRACT_ADDRESS') && (tx_logs_topic0 == '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef') && (tx_logs_topic3_int > 0)

In QuickAlerts, you can create custom expressions to place a custom WebHook on-chain. In the above example, we are using tx_logts_address variable to catch transaction logs for a particular address. SMART_CONTRACT_ADDRESS needs to be replaced with the address of the token smart contract. tx_logs_topic0 will filter the transactions which match the particular event type, here 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef is the hash form of the Transfer event and tx_logs_topic3_int > 0 simply means that all the token above 0 token id.

Some QuickAlerts Resources:

1

You should look into events.

ERC20/721 both emit an event on transfer. When listening at them, you can retrieve the transaction hash from that.

using ethersv6

const contract = new ethers.Contract(address, abi, provider);
const eventName = 'Transfer';
const eventFilter = contract.filters[eventName]();

contract.on(eventFilter, async (eventData) => { 
  //do something with the eventData
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.