UNPKG

@sky-mavis/tanto-widget

Version:
35 lines 1.31 kB
import {useEffect}from'react';import {useConfig}from'wagmi';import {WAYPOINT_ORIGINS}from'../../constants.mjs';import {authEventEmitter}from'../../hooks/useAuthEffect.mjs';import {isWaypointConnector}from'../../utils/walletDetection.mjs';function useWaypointMessageHandler(enableAuth) { const { connectors } = useConfig(); const waypointConnector = connectors.find(connector => isWaypointConnector(connector.id)); useEffect(() => { if (!enableAuth) return; const handleMessage = async ({ data, origin }) => { if (!WAYPOINT_ORIGINS.includes(origin)) return; if (data.method !== 'auth') return; const chainId = (await waypointConnector?.getChainId()) ?? 2020; if (data.type === 'success' && data.data) { const { address, id_token } = data.data; authEventEmitter.emit('success', { address, chainId, token: id_token }); } if (data.type === 'fail' && data.error) { authEventEmitter.emit('failed', { error: data.error }); } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); }, [enableAuth, waypointConnector]); }export{useWaypointMessageHandler};