Unable to integrate wallet service plugin

Hello team!

We are trying to add wallet service plugin but getting the error:
WalletServicesPluginError: Web3Auth is not connected

All packages are up to date. Would you please check the code snippet? Thanks in advance

import React, {createContext, ReactNode, useContext, useEffect, useState} from 'react';
import {ChainNamespaceType, IProvider, WEB3AUTH_NETWORK} from '@web3auth/base';
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { OpenloginAdapter, OpenloginUserInfo } from '@web3auth/openlogin-adapter';
import Web3, {Contract} from 'web3';
import {Web3Auth, Web3AuthOptions} from '@web3auth/modal';
import {RegisteredSubscription} from 'web3-eth';
import {CONTRACT_ESCROW, CONTRACT_USDT, contractABIEscrow, contractABIUSDT} from '@/src/context/constants';
import { WalletServicesPlugin } from "@web3auth/wallet-services-plugin";
import {getDefaultExternalAdapters} from '@web3auth/default-evm-adapter';

const clientId = ""; // get from https://dashboard.web3auth.io

const chainConfig = {
    chainNamespace: "eip155" as ChainNamespaceType,
    chainId: "0xCC", // hex of 1261120
    rpcTarget: "https://opbnb-mainnet-rpc.bnbchain.org",
    displayName: "opBNB Mainnet",
    blockExplorerUrl: "https://opbnbscan.com",
    ticker: "BNB",
    tickerName: "opBNB",
    logo: "https://cryptologos.cc/logos/bnb-bnb-logo.png",
};

const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });

const web3authOptions = {
    clientId,
    web3AuthNetwork:WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
    privateKeyProvider,
    uiConfig: {
        uxMode: 'redirect',
        mode: 'dark',
        logoDark: '',
        logoLight: '',
    },
    chainConfig: chainConfig,
};

type TInfo = {
    userInfo: Partial<OpenloginUserInfo> | null,
    balance: string | null,
    address: string | null,
}

type TWeb3Context = {
    provider: IProvider | null,
    web3auth: Web3Auth | null,
    info: TInfo,
    web3AuthIsLoading: boolean,
    balanceInUSDT: string;
    smartWeb3: Web3<RegisteredSubscription> | null,
    contractEscrow: Contract<any> | null,
    contractUSDT: Contract<any> | null,
    showCheckout: () => void;
    login: () => void;
}

export const Web3Context = createContext<TWeb3Context | null>(null);

type TWeb3ProviderProps = {
    children: ReactNode;
};

export const Web3Provider: React.FC<TWeb3ProviderProps> = ({ children }) => {
    const [provider, setProvider] = useState<IProvider | null>(null);
    const [web3auth, setWeb3auth] = useState<Web3Auth | null>(null);
    const [walletServicesPlugin, setWalletServicesPlugin] = useState<WalletServicesPlugin | null>(null);
    const [loggedIn, setLoggedIn] = useState(false);

    const [smartWeb3, setSmartWeb3] = useState<Web3<RegisteredSubscription> | null>(null);
    const [contractEscrow, setContractEscrow] = useState<Contract<any> | null>(null);
    const [contractUSDT, setContractUSDT] = useState<Contract<any> | null>(null);

    const [balanceInUSDT, setBalanceInUSDT] = useState('');

    const [info, setInfo] = useState<TInfo>({
        userInfo: null,
        balance: null,
        address: null,
    })

    useEffect(() => {
        const init = async () => {
            const web3auth = new Web3Auth(web3authOptions as Web3AuthOptions);

            const openloginAdapter = new OpenloginAdapter({
                adapterSettings: {
                    whiteLabel: {
                        logoLight: "https://web3auth.io/images/web3authlog.png",
                        logoDark: "https://web3auth.io/images/web3authlogodark.png",
                        defaultLanguage: "en", // en, de, ja, ko, zh, es, fr, pt, nl, tr
                        mode: "dark", // whether to enable dark, light or auto mode. defaultValue: auto [ system theme]б
                    },
                    clientId: clientId,
                    uxMode: 'redirect',
                    loginConfig: {
                        discord: {
                            verifier: "",
                            typeOfLogin: "",
                            clientId: "", //use your app client id you got from discord
                        },
                    },
                },
            });

            web3auth.configureAdapter(openloginAdapter);

            const walletServicesPlugin = new WalletServicesPlugin();
            setWalletServicesPlugin(walletServicesPlugin);
            web3auth.addPlugin(walletServicesPlugin);

            const adapters = await getDefaultExternalAdapters({ options: web3authOptions as Web3AuthOptions });
            adapters.forEach((adapter) => {
                web3auth.configureAdapter(adapter);
            });

            setWeb3auth(web3auth);

            await web3auth.initModal();

            if (web3auth.connected) {
                setLoggedIn(true);
                setProvider(web3auth.provider)
            }
        };

        init();
    }, []);

    const login = async () => {
        if (!web3auth) {
            console.log("web3auth not initialized yet");
            return;
        }
        await web3auth.connect();
    };


    // if web3auth is init and isConnected = true -> getUserInfo()
    // else -> login()
    useEffect(() => {
        (async() => {
            if (web3auth && web3auth.status === 'connected') {
                await getAllUserInfo()
            }
        })();
    }, [web3auth?.status]);

    useEffect(() => {
        (async() => {
            if (provider && info.address) {
                const web3 = new Web3(provider as any);
                setSmartWeb3(web3);

                const contractEscrow = new web3.eth.Contract(JSON.parse(JSON.stringify(contractABIEscrow)), CONTRACT_ESCROW);
                setContractEscrow(contractEscrow);
                const contractUSDT = new web3.eth.Contract(JSON.parse(JSON.stringify(contractABIUSDT)), CONTRACT_USDT);
                setContractUSDT(contractUSDT);

                const myAddress = (await web3.eth.getAccounts())[0];
                const checkedBalance = await contractUSDT.methods.balanceOf(myAddress).call() as string;
                const balanceInUSDT = web3.utils.fromWei(Number(checkedBalance), "ether");
                setBalanceInUSDT(balanceInUSDT);
            }
        })()

    }, [provider, info.address]);

    const getBalance = async () => {
        if (!provider) {
            console.log("provider not initialized yet");
            return;
        }
        const web3 = new Web3(provider as any);

        // Get user's Ethereum public address
        const address = (await web3.eth.getAccounts())[0];

        // Get user's balance in ether
        const balance = web3.utils.fromWei(
            await web3.eth.getBalance(address), // Balance is in wei
            "ether"
        );

        return {
            address,
            balance,
        }
    };

    const getAllUserInfo = async() => {
        try {
            const user = await web3auth?.getUserInfo();
            const balanceInfo = await getBalance();

            if (user && balanceInfo) {
                setInfo({
                    userInfo: user,
                    balance: balanceInfo.balance,
                    address: balanceInfo.address,
                });
            }
        } catch (error) {
            console.log(`getAllUserInfo:  ${error}`);
        }
    }

    const showCheckout = async () => {
        if (!walletServicesPlugin) {
            console.log('Error');
            return;
        }
        console.log(web3auth?.connected);
        await walletServicesPlugin.showCheckout();
    };

    const web3AuthIsLoading = web3auth ? web3auth.status !== 'connected' : false;

    return (
        <Web3Context.Provider value={{ web3auth, provider, info, web3AuthIsLoading, balanceInUSDT, smartWeb3, contractEscrow, contractUSDT, showCheckout, login }}>
            {children}
        </Web3Context.Provider>
    );
};

export const useWeb3 = () => {
    const context = useContext(Web3Context);
    if (!context) {
        throw new Error('useWeb3 must be used within a Web3Provider');
    }
    return context;
};

Hi @artur,

I hope you’re doing well! Which packages are you currently using? Could you try using version 8.3 and let me know if it resolves the issue? Feel free to reach out to me again whether it works or not. Thanks!

Thanks for your reply!
We are using 8.3 but we still have this issue :smiling_face_with_tear:

Dear @artur

Let dig inside the code to see more in deep the error. When is throwing you this error “WalletServicesPluginError: Web3Auth is not connected” in which line ?

Do you have an online repository to test it ?

Thanks

Unfortunately, we don’t have online repository.
Here the lines and where error occurs:

The error is thrown when calling any “serviceWallet” method, such as “showWalletUi(), showCheckout()” and others. Anywhere in the code, for example, here is a function to call:

const showCheckout = async () => {
if (!walletServicesPlugin) {
console.log(‘Error’);
return;
}
console.log(web3auth?.connected);
await walletServicesPlugin.showCheckout();
};

It is strange that at the same time “console.log(web3auth?.connected);” outputs the result “true”

also need to remark that we are using NextJS

Hi @artur,

The product team has identified the issue and is currently working to resolve it as quickly as possible. I’ll keep you updated as soon as we have a fix in place. Thank you both for your patience and understanding throughout this process.

Thanks a lot. Waiting for updates :+1:

Hello! Sorry for bothering you.

Just wondering, if there any updates?
Thanks!

hi @artur

Sorry, no news yet.

HI, we have the same problem. We are using following vanilla js scripts:

Authentication works without problem. Only wallet service gives “WalletServicesPluginError: Web3Auth is not connected” when executing walletServicesPlugin.showWalletUi();

Here are our initialization code:

// Init web3auth
const whiteLabel = {
    appName: 'Xyz',
    defaultLanguage: "en",
    logoLight: "https://web3auth.io/images/web3auth-logo.svg",
    logoDark: "https://web3auth.io/images/web3auth-logo---Dark.svg",
    mode: "light",
}

const chainConfig = {
    chainNamespace: "eip155",
    chainId: "0xaa36a7", // Please use 0x1 for Mainnet
    rpcTarget: "https://sepolia.infura.io/v3/{key}",
    displayName: "Seopolia Testnet",
    blockExplorer: "https://sepolia.etherscan.io/",
    ticker: "ETH",
    tickerName: "Ethereum Sepolia",
    uiConfig: whiteLabel
};

const privateKeyProvider = new window.EthereumProvider.EthereumPrivateKeyProvider({ config: { chainConfig } });
web3auth = new window.Modal.Web3Auth({
    clientId,
    privateKeyProvider,
    web3AuthNetwork: "sapphire_devnet"
});

// Add metamask adapter
const metamaskAdapter = new window.MetamaskAdapter.MetamaskAdapter({
    clientId,
    sessionTime: 3600, // 1 hour in seconds
    web3AuthNetwork: "sapphire_devnet",
    chainConfig: {
        chainNamespace: "eip155",
        chainId: "0xaa36a7",
        rpcTarget: "https://sepolia.infura.io/v3/{key}" 
    }
});
web3auth.configureAdapter(metamaskAdapter);

// Add wallet service plugin
walletServicesPlugin = new window.WalletServicesPlugin.WalletServicesPlugin();
web3auth.addPlugin(walletServicesPlugin); // Add the plugin to web3auth

await web3auth.initModal();

Thanks for your help.