I do it and its working
import React, { useCallback, useEffect, useState, ReactNode } from 'react'
import { ADAPTER_EVENTS, CHAIN_NAMESPACES, CONNECTED_EVENT_DATA, UserInfo, WEB3AUTH_NETWORK } from "@web3auth/base";
import { Web3Auth } from '@web3auth/modal';
import { LOGIN_MODAL_EVENTS } from "@web3auth/ui"
import Web3 from "web3";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { MetamaskAdapter } from "@web3auth/metamask-adapter";
const WEB3AUTH_CLIENT_ID = process.env.REACT_APP_WEB3_KEY || "";
export interface AuthProviderData {
web3auth: Web3Auth | null,
provider: CONNECTED_EVENT_DATA | null,
user: Partial<UserInfo> | null,
address: string | null,
isLogin: boolean;
onSuccessfulLogin: (data: CONNECTED_EVENT_DATA, user: Partial<UserInfo>, address: string) => void,
login: () => void,
logout: () => void,
cleanIsLogin: () => void,
}
export const AuthProviderContext = React.createContext<AuthProviderData>({
web3auth: null,
provider: null,
user: null,
address: null,
isLogin: false,
onSuccessfulLogin: (data: any) => { },
login: () => { },
logout: () => { },
cleanIsLogin: () => { },
});
const chainConfig = {
chainId: "0x1", // Please use 0x1 for Mainnet
rpcTarget: "https://rpc.ankr.com/eth",
chainNamespace: CHAIN_NAMESPACES.EIP155,
displayName: "Ethereum Mainnet",
blockExplorerUrl: "https://etherscan.io/",
ticker: "ETH",
tickerName: "Ethereum",
logo: "https://images.toruswallet.io/eth.svg"
};
const privateKeyProvider = new EthereumPrivateKeyProvider({
config: { chainConfig: chainConfig }
});
const web3auth = new Web3Auth({
clientId: WEB3AUTH_CLIENT_ID,
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_DEVNET,
privateKeyProvider: privateKeyProvider,
uiConfig: {
appName: "iPal",
mode: "auto"
},
});
const metamaskAdapter = new MetamaskAdapter({
clientId: WEB3AUTH_CLIENT_ID,
sessionTime: 3600, // 1 hour in seconds
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_DEVNET,
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the public RPC we have added, please pass on your own endpoint while creating an app
},
});
// it will add/update the metamask adapter in to web3auth class
web3auth.configureAdapter(metamaskAdapter);
// You can change the adapter settings by calling the setAdapterSettings() function on the adapter instance.
metamaskAdapter.setAdapterSettings({
sessionTime: 86400, // 1 day in seconds
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the public RPC we have added, please pass on your own endpoint while creating an app
},
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_DEVNET,
});
// const web3auth = new Web3Auth({
// clientId: WEB3AUTH_CLIENT_ID,
// web3AuthNetwork: "sapphire_devnet",
// chainConfig: {
// chainId: "0x1",
// rpcTarget: "https://rpc.ankr.com/eth",
// chainNamespace: CHAIN_NAMESPACES.EIP155,
// displayName: "Ethereum Mainnet",
// blockExplorer: "https://etherscan.io/",
// ticker: "ETH",
// tickerName: "Ethereum",
// },
// uiConfig: {
// appName: "iPal",
// mode: "auto"
// },
// });
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [provider, setProvider] = useState<CONNECTED_EVENT_DATA | null>(null);
const [user, setUser] = useState<Partial<UserInfo> | null>(null);
const [address, setAddress] = useState<string | null>(null);
const [isLogin, setIsLogin] = useState<boolean>(false);
const onSuccessfulLogin = useCallback((data: CONNECTED_EVENT_DATA, user: Partial<UserInfo>, address: string) => {
// console.log('onSuccessfulLogin', data, user, address);
setProvider(data);
setUser(user);
setAddress(address);
}, [])
const cleanIsLogin = () => {
setIsLogin(false);
};
const login = useCallback(() => {
web3auth.connect().then(() => {
setIsLogin(true);
}).catch(err => {
console.log(err)
})
}, [])
const logout = useCallback(() => {
setUser(null);
setProvider(null);
setAddress(null);
web3auth.logout().then(() => {
// login on logout
}).catch(err => {
console.log('logout', err)
})
}, [])
const subscribeAuthEvents = useCallback((web3auth: Web3Auth) => {
web3auth.on(ADAPTER_EVENTS.CONNECTED, (data: CONNECTED_EVENT_DATA) => {
// console.log("Yeah!, you are successfully logged in", data);
const web3 = new Web3(web3auth.provider as any);
web3.eth.getAccounts().then((address) => {
// GET BALANCE
// web3.eth.getBalance(address[0]).then((value) => {
// const balance = web3.utils.fromWei(value ,"ether");
// console.log("balance: ", balance);
// })
web3auth.getUserInfo().then((user) => {
onSuccessfulLogin(data, user, address[0])
})
})
});
web3auth.on(ADAPTER_EVENTS.CONNECTING, () => {
console.log("connecting");
});
web3auth.on(ADAPTER_EVENTS.DISCONNECTED, () => {
console.log("disconnected");
web3auth.clearCache();
setUser(null);
setProvider(null);
setAddress(null);
localStorage.clear();
});
web3auth.on(ADAPTER_EVENTS.ERRORED, (error) => {
console.log("some error or user have cancelled login request", error);
});
web3auth.on(LOGIN_MODAL_EVENTS.MODAL_VISIBILITY, (isVisible) => {
console.log("modal visibility", isVisible);
});
}, [onSuccessfulLogin])
useEffect(() => {
subscribeAuthEvents(web3auth);
web3auth.initModal().catch(err => {
alert('error' + err)
})
console.log(web3auth);
}, [])
const ctx: AuthProviderData = {
web3auth,
provider,
user,
address,
isLogin,
cleanIsLogin,
onSuccessfulLogin,
login,
logout,
}
return (
<AuthProviderContext.Provider value={ctx}>
{children}
</AuthProviderContext.Provider>
)
}
export const AuthConsumer = AuthProviderContext.Consumer```