Content from Web3Auth Community
This topic was originally posted by chaudharikaushal02 on 12/12/2024.
This content has been migrated from our previous community forum to preserve valuable discussions.
// Web3AuthProvider.jsx
import React, { createContext, useContext, useState, useEffect } from “react”;
import { Web3Auth } from “@web3auth/modal”;
import { CHAIN_NAMESPACES } from “@web3auth/base”;
import { OpenloginAdapter } from “@web3auth/openlogin-adapter”;
import { EthereumPrivateKeyProvider } from “@web3auth/ethereum-provider”;
const Web3AuthContext = createContext();
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: “0xaa36a7”,
rpcTarget: “https://rpc.ankr.com/eth_sepolia”,
// Avoid using public rpcTarget in production.
// Use services like Infura, Quicknode etc
displayName: “Ethereum Sepolia Testnet”,
blockExplorerUrl: “https://sepolia.etherscan.io”,
ticker: “ETH”,
tickerName: “Ethereum”,
logo: “https://cryptologos.cc/logos/ethereum-eth-logo.png”,
};
const Web3AuthProvider = ({ children }) => {
const [web3auth, setWeb3auth] = useState(null);
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [isReady, setIsReady] = useState(false);
const [initializationError, setInitializationError] = useState(null);
useEffect(() => {
let mounted = true;
const init = async () => { try { const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig }, });const web3auth = new Web3Auth({ clientId: "BAuX9b2uRpOyTHye2LXca5ocgI5hG4q-usWtp6QL9Bm2Ezd2XvpH3LjWhSKwalqdc_EA68btSnwpi--_qtBenhw", web3AuthNetwork: "sapphire_devnet", chainConfig: chainConfig, privateKeyProvider, enableLogging: false, }); web3auth.on("connected", async () => { console.log("Web3Auth connected"); if (mounted) { setIsReady(true); try { const userData = await web3auth.getUserInfo(); const userType = localStorage.getItem("userType"); if (userType) { setUser({ ...userData, type: userType }); } } catch (error) { console.warn("Error getting user info:", error); } } }); web3auth.on("disconnected", () => { if (mounted) { setUser(null); localStorage.removeItem("userType"); setIsReady(true); } }); const openloginAdapter = new OpenloginAdapter({ privateKeyProvider, chainConfig: chainConfig, adapterSettings: { network: "sapphire_devnet", iframeUrl: "https://beta.openlogin.com", uxMode: "popup", loginConfig: { jwt: { verifier: "contract-dapp-test", typeOfLogin: "jwt", clientId: "595659542544-213hls7eoaft0u5scu2ab00o5b4uip62.apps.googleusercontent.com", }, }, }, }); web3auth.configureAdapter(openloginAdapter); // Initialize with retries let initRetries = 0; const maxRetries = 3; let initialized = false; while (initRetries < maxRetries && !initialized && mounted) { try { await web3auth.initModal(); initialized = true; if (mounted) { setWeb3auth(web3auth); setIsReady(true); setInitializationError(null); } } catch (error) { initRetries++; console.warn( `Initialization attempt ${initRetries} failed:`, error ); if (initRetries === maxRetries) { if (mounted) { setInitializationError( "Failed to initialize Web3Auth. Please refresh the page and try again." ); } } else { await new Promise((resolve) => setTimeout(resolve, 1500)); } } }} catch (error) {
console.error(“Error in Web3Auth setup:”, error);
if (mounted) {
setInitializationError(
“Failed to setup Web3Auth. Please check your connection and try again.”
);
}
} finally {
if (mounted) {
setIsLoading(false);
}
}
};init();
return () => {
mounted = false;
if (web3auth) {
web3auth.removeAllListeners();
}
};
}, []);
const login = async (selectedUserType) => {
if (!web3auth) {
throw new Error(“Web3Auth not initialized yet. Please wait…”);
}
if (!isReady) { throw new Error("Please wait while we set up your secure connection..."); }try {
const web3authProvider = await web3auth.connect();
if (!web3authProvider) {
throw new Error(“Could not connect to wallet. Please try again.”);
}const userData = await web3auth.getUserInfo();
const userWithType = { …userData, type: selectedUserType };localStorage.setItem(“userType”, selectedUserType);
setUser(userWithType);
return userWithType;
} catch (error) {
console.error(“Login error:”, error);
localStorage.removeItem(“userType”);
throw new Error(
error.message || “Failed to connect wallet. Please try again.”
);
}
};
const logout = async () => {
if (!web3auth) {
throw new Error(“Web3Auth not initialized”);
}
await web3auth.logout();
setUser(null);
localStorage.removeItem("userType");
};
return (
<Web3AuthContext.Provider
value={{ user, login, logout, isLoading, isReady, initializationError }}
>
{children}
</Web3AuthContext.Provider>
);
};
const useWeb3Auth = () => {
const context = useContext(Web3AuthContext);
if (!context) {
throw new Error(“useWeb3Auth must be used within a Web3AuthProvider”);
}
return context;
};
export { Web3AuthProvider, useWeb3Auth };
this above is my web3auth provider code , error is Error: unspecified network and iframeUrl i m using the sapphire_devnet, is this used for the testing in my local environment
please give the solution

