0

I am trying to check if a certain wallet has an NFT from a contract.

I am using the following libraries:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@walletconnect/[email protected]/lib/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@walletconnect/[email protected]/lib/index.min.js"></script><!--

I tried the following:


window.addEventListener('DOMContentLoaded', (event) => {
    var WalletConnect = window.WalletConnect.default;
    var WalletConnectQRCodeModal = window.WalletConnectQRCodeModal.default;

    // Display all
    var displayData = async function (payload) { 
        console.log("connected")
        console.log(payload)


        let icyContract = "0x37d754D6D1668e32678fbeb2604Da9CB4fBe993F"
        let response = await fetch('./icyfounderclub_abi.json')
        let abiRes = await response.json();
        let abi = JSON.parse(abiRes["result"])

        let walletAddress = "";
        if (typeof payload === 'undefined') {
            walletAddress = "0x26195376410c52c9622037250d070a19ef04e513";
        } else {
            walletAddress = payload["params"][0]["accounts"][0];
        }
        const web3 = new Web3(window.ethereum)      
        
        const contract = new web3.eth.Contract(abi, icyContract)
        contract.defaultAccount = walletAddress

        // get balance of how many nfts you have
        const balance = await contract.methods.balanceOf(walletAddress).call() // <--- Here I get the error!!!

        console.log(balance)

        for(let i = 0; i < balance; i++) {
            const tokenId = await contract.methods.tokenOfOwnerByIndex(walletAddress, i).call()
        
            let tokenMetadataURI = await contract.methods.tokenURI(tokenId).call()

            if(tokenMetadataURI.startsWith("ipfs://")) {
                tokenMetadataURI = `https://ipfs.io/ipfs${tokenMetadataURI.split("ipfs://")[1]}`
            }

            const tokenMetadata = await fetch(tokenMetadata).then((response) => response.json())
            console.log(tokenMetadata["image"])

        }
    }


    // Get an instance of the WalletConnect connector
    var walletConnector = new WalletConnect({
        bridge: 'https://bridge.walletconnect.org' // Required
    });

    // Display data if connected
    if (walletConnector.connected) {
        displayData();
    }

    // When the connect/disconnect button is clicked
    connect = function () { // Check if connection is already established
        if (! walletConnector.connected) { // create new session
            walletConnector.createSession().then(() => { // get uri for QR Code modal
                var uri = walletConnector.uri;
                // display QR Code modal
                WalletConnectQRCodeModal.open(uri, () => {
                    console.log('QR Code Modal closed');
                });
            });
        } else { // disconnect
                walletConnector.killSession();
        }
    }

    // Subscribe to connection events: connect, session_update and disconnect
    walletConnector.on('connect', function (error, payload) {
        if (error) {
            console.error(error);
        } else { // Close QR Code Modal
            WalletConnectQRCodeModal.close();
            // connection is made so we can display all the data
            displayData(payload);
        }
    });

    walletConnector.on('session_update', function (error, payload) {
        if (error) {
            console.error(error);
        } else if (walletConnector.connected) { // data may be changed
            displayData();
        }

    });

    walletConnector.on('disconnect', function (error, payload) {
        if (error) {
            console.error(error);
        } else {
            // remove all the data
        }
    });
});

This is the contract I am checking against: https://etherscan.io/address/0x37d754d6d1668e32678fbeb2604da9cb4fbe993f#code

Here I get the error:

  const balance = await contract.methods.balanceOf(walletAddress).call()

This is the error:

Uncaught Error Error: Provider not set or invalid
    at InvalidProvider (/home/myProject/packages/web3-core-helpers/lib/errors.js:39:16)
    at c.send (/home/myProject/packages/web3-core-requestmanager/lib/index.js:145:32)
    at c (/home/myProject/packages/web3-core-method/lib/index.js:629:42)
    at n (/home/myProject/packages/web3-core-method/lib/index.js:661:13)
    at y._executeMethod (/home/myProject/packages/web3-eth-contract/lib/index.js:810:20)
    at eval (<eval>/VM46947625:1:43)
    at displayData (/home/myProject/script.js:33:40)
    --- setTimeout ---
    at _fireError (/home/myProject/packages/web3-utils/lib/index.js:63:9)
    at a (/home/myProject/packages/web3-core-method/lib/index.js:553:30)
    at c.send (/home/myProject/packages/web3-core-requestmanager/lib/index.js:145:16)
    at c (/home/myProject/packages/web3-core-method/lib/index.js:629:42)
    at n (/home/myProject/packages/web3-core-method/lib/index.js:661:13)
    at y._executeMethod (/home/myProject/packages/web3-eth-contract/lib/index.js:810:20)
    at eval (<eval>/VM46947625:1:43)
    at displayData (/home/myProject/script.js:33:40)
    --- await ---
    at <anonymous> (/home/myProject/script.js:69:9)
Uncaught Error Error: Provider not set or invalid
    at InvalidProvider (/home/myProject/packages/web3-core-helpers/lib/errors.js:39:16)
    at c.send (/home/myProject/packages/web3-core-requestmanager/lib/index.js:145:32)
    at c (/home/myProject/packages/web3-core-method/lib/index.js:629:42)
    at n (/home/myProject/packages/web3-core-method/lib/index.js:661:13)
    at y._executeMethod (/home/myProject/packages/web3-eth-contract/lib/index.js:810:20)
    at displayData (/home/myProject/script.js:33:73)
    --- await ---
    at <anonymous> (/home/myProject/script.js:69:9)

I tried setting the provider the following: const web3 = new Web3(window.ethereum)

However this does not seem to work.

Any suggestions why I get this error?

3 Answers 3

1

Don't know if it helps you but i use this code on javascript to NFT balances and tokenID's ownded by an address:

//A RETURN FUNCTION OR AN API MIDDLEWARE
    const balance = await erc721.balanceOf(walletAddress);


    const getTokensId = async (recipient, index) => {
        try {
            const result = nonfungibleManager.tokenOfOwnerByIndex(recipient, index);
            return result;
        } catch (error) {
            console.log(error, "the error for getTokensId");
        }
    };

    const getPosition = async (id) => {
        try {
            const position = erc721.positions(id);
            return position;
        } catch (error) {
            console.log(error, "error from getPosition");
        }
    };

    let nfts = [];

    let numbers = [];
    for (let i = 0; i < Number(balance._hex); i++) {
        numbers.push(i);
    }
    await Promise.all(
        numbers.map(async (i) => {
            await getTokensId(walletAddress, i).then(async (res) => {
                let tokenId = Number(res?._hex);
                await getPosition(tokenId).then((result) => {
                    nfts.push({
                        'tokenId': tokenId
                    });
                });
            });
        })
    );

return nfts

//END

1

You can check out the getWalletNFTs endpoint provided by Moralis. You will get all the NFTs owned by a wallet address.

Here is an example of how to implement this step by step https://docs.moralis.io/web3-data-api/evm/how-to-get-all-nfts-owned-by-an-address

Let me know if you need any help!

0

I think you can try the following to inject a dedicated web3js object and use that to send transactions.

const Web3 = require("web3");
    if (window.ethereum) {
        await window.ethereum.enable();
        window.web3 = new Web3(window.ethereum);    
        const txn = window.web3.eth.sendTransaction([PARAMS]);
    }
3
  • I do not want to send a trx, I just want to check the balanceOf a wallet address. In my code I already injected new Web3(window.ethereum);
    – Carol.Kar
    Dec 27, 2022 at 10:17
  • I mean you have the object you can refer to and use it to send any specific requests. So create a contract object and try interaction with it? Dec 27, 2022 at 10:18
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 29, 2022 at 9:58

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.