简体   繁体   中英

Ethers.js: ReferenceError: utils is not defined

I'm trying to create a listener for incoming transactions with ethers.js (v5.6). According to the docs , to listen to incoming transactions you need to create this filter:

// List all token transfers  *to*  myAddress:
filter = {
    address: tokenAddress,
    topics: [
        utils.id("Transfer(address,address,uint256)"),
        null,
        hexZeroPad(myAddress, 32)
    ]
};

Having this in my script gives me an error saying utils.id("Transfer(address,address,uint256)"), ReferenceError: utils is not defined . I can't find anything in the docs about importing an utils package. Can anyone sort me out?

My full code:

async function incomingTransactions() {
    if (loadedUser) {
        console.log("User loaded", loadedUser)
        let myAddress = loadedUser.publicKey
        let filter = {
            address: myAddress,
            topics: [
                utils.id("Transfer(address,address,uint256)"),
                null,
                hexZeroPad(myAddress, 32)
            ]
        };

        // let foo = await provider.getLogs(filter)
        // console.log(foo)
    } 
    console.log("No user loaded")
}

const interval = setInterval(function() {
    incomingTransactions();
}, 5000);
 

Looks like utils is part of the ethers object, and hexZeroPad and id are part of utils so you can use them like so:

const { ethers } = require("ethers"); // assuming commonjs

ethers.utils.id("Transfer(address,address,uint256)");
ethers.utils.hexZeroPad(myAddress, 32);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM