@web3auth/modal
Version:
Multi chain wallet aggregator for web3Auth
70 lines (67 loc) • 2.49 kB
JavaScript
import { EVM_PLUGINS, CONNECTOR_STATUS, PLUGIN_EVENTS } from '@web3auth/no-modal';
import { createContext, useContext, useState, useEffect, useMemo, createElement } from 'react';
const WalletServicesContext = /*#__PURE__*/createContext(null);
function WalletServicesContextProvider({
children,
context
}) {
const web3AuthContext = useContext(context);
const {
getPlugin,
isInitialized,
isConnected
} = web3AuthContext;
const [ready, setReady] = useState(false);
const [connecting, setConnecting] = useState(false);
const [walletServicesPlugin, setWalletServicesPlugin] = useState(null);
useEffect(() => {
if (isInitialized) {
const plugin = getPlugin(EVM_PLUGINS.WALLET_SERVICES);
setWalletServicesPlugin(plugin);
}
}, [isInitialized, getPlugin]);
useEffect(() => {
if (isConnected) {
const plugin = getPlugin(EVM_PLUGINS.WALLET_SERVICES);
setWalletServicesPlugin(plugin);
// when rehydrating, the connectedListener may be registered after the connected event is emitted, we need to check the status here
if ((plugin === null || plugin === void 0 ? void 0 : plugin.status) === CONNECTOR_STATUS.CONNECTED) setReady(true);
}
}, [isConnected, getPlugin, walletServicesPlugin]);
useEffect(() => {
const connectedListener = () => {
setReady(true);
setConnecting(false);
};
const disconnectedListener = () => {
setReady(false);
setConnecting(false);
};
const connectingListener = () => {
setConnecting(true);
};
if (walletServicesPlugin) {
walletServicesPlugin.on(PLUGIN_EVENTS.CONNECTED, connectedListener);
walletServicesPlugin.on(PLUGIN_EVENTS.DISCONNECTED, disconnectedListener);
walletServicesPlugin.on(PLUGIN_EVENTS.CONNECTING, connectingListener);
}
return () => {
if (walletServicesPlugin) {
walletServicesPlugin.off(PLUGIN_EVENTS.CONNECTED, connectedListener);
walletServicesPlugin.off(PLUGIN_EVENTS.DISCONNECTED, disconnectedListener);
walletServicesPlugin.off(PLUGIN_EVENTS.CONNECTING, connectingListener);
}
};
}, [walletServicesPlugin]);
const value = useMemo(() => {
return {
plugin: walletServicesPlugin,
ready,
connecting
};
}, [walletServicesPlugin, ready, connecting]);
return /*#__PURE__*/createElement(WalletServicesContext.Provider, {
value
}, children);
}
export { WalletServicesContext, WalletServicesContextProvider };