UNPKG

@dynamic-labs/sdk-react-core

Version:

A React SDK for implementing wallet web3 authentication and authorization to your website.

260 lines (257 loc) 13.4 kB
'use client' import { useRef, useMemo, useEffect } from 'react'; import { walletConnectorEvents } from '@dynamic-labs/wallet-connector-core'; import { getWalletConnectorConstructorOptions } from '@dynamic-labs/multi-wallet'; import { ChainRpcProviders } from '@dynamic-labs/rpc-providers'; import { isWalletBookPopulated } from '@dynamic-labs/wallet-book'; import { useWalletItemActions } from '../../utils/hooks/useWalletItemActions/useWalletItemActions.js'; import '../../context/DynamicContext/DynamicContext.js'; import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js'; import '@dynamic-labs/sdk-api-core'; import { logger } from '../../shared/logger.js'; import '@dynamic-labs/iconic'; import 'react/jsx-runtime'; import '../../context/ViewContext/ViewContext.js'; import { createWallet } from '../../shared/utils/functions/wallet/createWallet.js'; import '@dynamic-labs/utils'; import '../../utils/constants/colors.js'; import '../../utils/constants/values.js'; import '../../shared/consts/index.js'; import '../../events/dynamicEvents.js'; import '../../../../_virtual/_tslib.js'; import '../../context/CaptchaContext/CaptchaContext.js'; import '../../context/ErrorContext/ErrorContext.js'; import 'react-international-phone'; import '../../store/state/nonce/nonce.js'; import '../../store/state/projectSettings/projectSettings.js'; import '../../config/ApiEndpoint.js'; import '../../store/state/user/user.js'; import '../../locale/locale.js'; import '../../store/state/dynamicContextProps/dynamicContextProps.js'; import '../../store/state/primaryWalletId/primaryWalletId.js'; import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js'; import '../../context/AccessDeniedContext/AccessDeniedContext.js'; import '../../context/AccountExistsContext/AccountExistsContext.js'; import '../../context/UserWalletsContext/UserWalletsContext.js'; import '../../store/state/authMode/authMode.js'; import '../../context/VerificationContext/VerificationContext.js'; import 'react-dom'; import '../../utils/functions/compareChains/compareChains.js'; import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js'; import '../../context/ThemeContext/ThemeContext.js'; import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js'; import 'bs58'; import '@dynamic-labs/types'; import '../../context/SocialRedirectContext/SocialRedirectContext.js'; import '../../context/LoadingContext/LoadingContext.js'; import '../../context/WalletContext/WalletContext.js'; import '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js'; import 'yup'; import '../../context/MockContext/MockContext.js'; import '../../views/CollectUserDataView/useFields.js'; import '../../context/FieldsStateContext/FieldsStateContext.js'; import '../../context/UserFieldEditorContext/UserFieldEditorContext.js'; import { getWalletConnectorOptions, mergeWalletConnectorOptions } from '../../store/state/walletOptions/walletOptions.js'; import 'react-i18next'; import '../Accordion/components/AccordionItem/AccordionItem.js'; import '../Alert/Alert.js'; import '../ShadowDOM/ShadowDOM.js'; import '../IconButton/IconButton.js'; import '../InlineWidget/InlineWidget.js'; import '../Input/Input.js'; import '../IsBrowser/IsBrowser.js'; import '../MenuList/Dropdown/Dropdown.js'; import '../OverlayCard/OverlayCard.js'; import '../Transition/ZoomTransition/ZoomTransition.js'; import '../Transition/SlideInUpTransition/SlideInUpTransition.js'; import '../Transition/OpacityTransition/OpacityTransition.js'; import '../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js'; import '../Popper/Popper/Popper.js'; import '../Popper/PopperContext/PopperContext.js'; import 'react-focus-lock'; import 'qrcode'; import 'formik'; import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js'; import '../../context/WalletGroupContext/WalletGroupContext.js'; import '../../context/IpConfigurationContext/IpConfigurationContext.js'; import '../../context/ConnectWithOtpContext/ConnectWithOtpContext.js'; import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js'; import '@hcaptcha/react-hcaptcha'; import '../../widgets/DynamicWidget/context/DynamicWidgetContext.js'; import '../../context/FooterAnimationContext/index.js'; import '../../context/ErrorContext/hooks/useErrorText/useErrorText.js'; import '../../context/PasskeyContext/PasskeyContext.js'; import '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js'; import '../../store/state/sendBalances.js'; import { setConnectorInitializing } from '../../store/state/connectorsInitializing/connectorsInitializing.js'; import '../OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js'; import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js'; import '../../views/TransactionConfirmationView/TransactionConfirmationView.js'; import '../../widgets/DynamicWidget/views/ManagePasskeysWidgetView/PasskeyCard/PasskeyCard.js'; import '../../context/OnrampContext/OnrampContext.js'; import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js'; import '../../../index.js'; import '../../store/state/tokenBalances.js'; import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js'; import { useInternalDynamicContext } from '../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js'; const WalletConnectorEvents = ({ connectorProps, }) => { const { primaryWallet } = useInternalDynamicContext(); const { handleWalletItemClick } = useWalletItemActions(); const pendingConstructorRef = useRef([]); const injectedDebounceTimeoutRef = useRef(); const pendingReadyConnectorsRef = useRef([]); const readyDebounceTimeoutRef = useRef(); // need to add the timeout to ensure the setConnectorInitializing call is // not made in the same tick to avoid a bad setState call error from React const waitAndSetState = (func) => { setTimeout(() => { func(); }, 0); }; const walletConnectorConstructorOptions = useMemo(() => { var _a, _b; if (!connectorProps.projectSettings || !connectorProps.networkConfigurations || !isWalletBookPopulated(connectorProps.walletBook)) { return; } return getWalletConnectorConstructorOptions(Object.assign(Object.assign({}, connectorProps), { chainRpcProviders: ChainRpcProviders, settings: connectorProps.projectSettings, walletConnectProjectId: (_b = (_a = connectorProps.projectSettings) === null || _a === void 0 ? void 0 : _a.sdk.walletConnect) === null || _b === void 0 ? void 0 : _b.projectId })); }, [connectorProps]); // add listener for providerInjected event useEffect(() => { const processPendingConstructors = () => { if (pendingConstructorRef.current.length === 0) { return; } logger.debug('[WalletConnectorEvents] processPendingConstructors', { pendingConstructors: pendingConstructorRef.current, }); pendingConstructorRef.current.forEach((injectedConnectorConstructor) => { if (!walletConnectorConstructorOptions) return; const injectedConnector = new injectedConnectorConstructor(walletConnectorConstructorOptions); logger.debug('[WalletConnectorEvents] handleProviderInjected', { injectedConnector, }); walletConnectorEvents.emit('providerReady', { connector: injectedConnector, }); }); pendingConstructorRef.current = []; }; const handleProviderInjected = ({ injectedConnectorConstructor, }) => { pendingConstructorRef.current.push(injectedConnectorConstructor); if (injectedDebounceTimeoutRef.current) { clearTimeout(injectedDebounceTimeoutRef.current); } injectedDebounceTimeoutRef.current = setTimeout(() => { processPendingConstructors(); }, 100); // 100ms debounce window }; walletConnectorEvents.on('providerInjected', handleProviderInjected); return () => { walletConnectorEvents.off('providerInjected', handleProviderInjected); if (injectedDebounceTimeoutRef.current) { clearTimeout(injectedDebounceTimeoutRef.current); } // Process any remaining constructors on cleanup processPendingConstructors(); }; }, [walletConnectorConstructorOptions]); // add listener for providerReady event useEffect(() => { const processReadyConnectors = () => { if (pendingReadyConnectorsRef.current.length === 0) { return; } logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] processReadyConnectors', { connectors: pendingReadyConnectorsRef.current, }); const walletConnectorOptions = getWalletConnectorOptions(); const updatedConnectors = [...walletConnectorOptions]; pendingReadyConnectorsRef.current.forEach((connector) => { let foundWallet = false; for (let i = 0; i < updatedConnectors.length; i++) { if (updatedConnectors[i].key === connector.key) { foundWallet = true; updatedConnectors[i] = Object.assign(Object.assign({}, updatedConnectors[i]), { isInstalledOnBrowser: connector.isInstalledOnBrowser(), walletConnector: connector }); break; } } if (!foundWallet) { const newWalletOption = createWallet(connectorProps.walletBook, connector); updatedConnectors.push(newWalletOption); } }); mergeWalletConnectorOptions(updatedConnectors); pendingReadyConnectorsRef.current = []; }; const handleProviderReady = ({ connector, }) => { logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleProviderReady', { connector, }); pendingReadyConnectorsRef.current.push(connector); if (readyDebounceTimeoutRef.current) { clearTimeout(readyDebounceTimeoutRef.current); } readyDebounceTimeoutRef.current = setTimeout(() => { processReadyConnectors(); }, 100); // 100ms debounce window }; if (!isWalletBookPopulated(connectorProps.walletBook)) { return; } walletConnectorEvents.on('providerReady', handleProviderReady); return () => { walletConnectorEvents.off('providerReady', handleProviderReady); if (readyDebounceTimeoutRef.current) { clearTimeout(readyDebounceTimeoutRef.current); } // Process any remaining connectors on cleanup processReadyConnectors(); }; }, [connectorProps.walletBook]); // add listener for autoConnect event useEffect(() => { const handleAutoConnect = ({ connector, }) => { logger.debug('[WalletConnectorEvents] handleAutoConnect', { connector }); const walletConnectorOptions = getWalletConnectorOptions(); const walletOption = walletConnectorOptions.find((wallet) => wallet.walletConnector.key === connector.key); logger.debug('[WalletConnectorEvents] handleAutoConnect - found walletOption', Boolean(walletOption)); if (!walletOption) return; handleWalletItemClick(walletOption); }; // if there's a connected wallet, we should not auto connect another wallet if (primaryWallet) { return; } walletConnectorEvents.on('autoConnect', handleAutoConnect); return () => { walletConnectorEvents.off('autoConnect', handleAutoConnect); }; }, [handleWalletItemClick, primaryWallet]); // add listener for connectorInitStarted and connectorInitCompleted events useEffect(() => { const handleConnectorInitStarted = (key) => { logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleConnectorInitStarted', { key }); waitAndSetState(() => { setConnectorInitializing(key, true); }); }; const handleConnectorInitCompleted = (key) => { logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleConnectorInitCompleted', { key }); waitAndSetState(() => { setConnectorInitializing(key, false); }); }; walletConnectorEvents.on('connectorInitStarted', handleConnectorInitStarted); walletConnectorEvents.on('connectorInitCompleted', handleConnectorInitCompleted); return () => { walletConnectorEvents.off('connectorInitStarted', handleConnectorInitStarted); walletConnectorEvents.off('connectorInitCompleted', handleConnectorInitCompleted); }; }, []); return null; }; export { WalletConnectorEvents };