UNPKG

@broxus/tvm-connect

Version:

Nekoton-compatible wallets connector.

62 lines (61 loc) 2.11 kB
import { debug, isBrowser, storage } from '@broxus/js-utils'; import * as React from 'react'; import { TVM_RECENT_CONNECTION } from '../constants'; import { useTvmWalletProviders } from '../context'; import { ConnectionType } from '../types'; function isRecentConnectionMeta(value) { const meta = { providerId: value.providerId, type: value.type }; return Boolean(meta.type && ConnectionType[meta.type] && !!meta.providerId); } export function storeRecentConnectionMeta(meta, storageKey = TVM_RECENT_CONNECTION) { if (!meta) { storage.remove(storageKey); return; } debug('Store TVM recent connection', meta); storage.set(storageKey, JSON.stringify(meta)); } export function getRecentConnectionMeta(storageKey = TVM_RECENT_CONNECTION) { const value = storage.get(storageKey); if (!value) { return undefined; } try { const json = JSON.parse(value); if (isRecentConnectionMeta(json)) { return json; } } catch (e) { debug(e); } storeRecentConnectionMeta(undefined, storageKey); return undefined; } export function useRecentConnectionMeta() { const walletProviders = useTvmWalletProviders(); const storageKey = walletProviders.recentMetaStorageKey ?? TVM_RECENT_CONNECTION; const [recentMeta, setRecentMeta] = React.useState(getRecentConnectionMeta(storageKey)); const setMeta = (meta) => { storeRecentConnectionMeta(meta, storageKey); }; React.useEffect(() => { const onStorage = (event) => { if (event.key === storageKey && event.newValue) { const json = JSON.parse(event.newValue); if (isRecentConnectionMeta(json)) { setRecentMeta(json); } } }; if (isBrowser()) { window.addEventListener('storage', onStorage); } return () => { if (isBrowser()) { window.removeEventListener('storage', onStorage); } }; }, [storageKey]); return [recentMeta, setMeta]; }