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;
};