@web3-react/core#useWeb3React TypeScript Examples
The following examples show how to use
@web3-react/core#useWeb3React.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetworkButton.tsx From dxvote with GNU Affero General Public License v3.0 | 6 votes |
NetworkButton = () => {
const [isNetworkModalOpen, setIsNetworkModalOpen] = useState(false);
const { chainId, error } = useWeb3React();
const chainName =
getChains().find(chain => chain.id === chainId)?.displayName || null;
const toggleNetworkModal = () => {
setIsNetworkModalOpen(!isNetworkModalOpen);
};
function getNetworkStatus() {
if ((chainId && !isChainIdSupported(chainId)) || error) {
return <Button onClick={toggleNetworkModal}>Unsupported Network</Button>;
} else if (chainId) {
return (
<IconButton onClick={toggleNetworkModal} iconLeft>
<ButtonIcon src={iconsByChain[chainId]} alt={'Icon'} />
{chainName}
</IconButton>
);
} else {
return (
<Button onClick={toggleNetworkModal} active={true}>
Not Connected
</Button>
);
}
}
return (
<>
{getNetworkStatus()}
<NetworkModal isOpen={isNetworkModalOpen} onClose={toggleNetworkModal} />
</>
);
}
Example #2
Source File: useEagerConnect.ts From index-ui with MIT License | 6 votes |
export default function useEagerConnect(
connect: (walletType: string) => Promise<void>
) {
const { active } = useWeb3React()
const [tried, setTried] = useState(false)
// Connect to existing injected provider if app was opened from ONTO mobile wallet
useEffect(() => {
if (!active && !tried && (window as any).ethereum?.isONTO) {
connect('injected').catch(() => {
setTried(true)
})
}
}, [connect, active, tried])
// wait until we get confirmation of a connection to flip the flag
useEffect(() => {
if (active) {
setTried(true)
}
}, [active])
return tried
}
Example #3
Source File: Account.tsx From hypertext with GNU General Public License v3.0 | 6 votes |
function ETHBalance(): JSX.Element {
const { account } = useWeb3React()
const { data } = useETHBalance(account, true)
const [showUSD] = useShowUSD()
const USDETHPrice = useUSDETHPrice()
return (
<Button
variant="outline"
cursor="default"
tabIndex={-1}
_hover={{}}
_active={{}}
_focus={{}}
style={{ borderTopRightRadius: 0, borderBottomRightRadius: 0, borderRight: 'none' }}
>
Ξ{' '}
{showUSD && USDETHPrice
? `$${(data as TokenAmount).multiply(USDETHPrice).toFixed(2, { groupSeparator: ',' })}`
: (data as TokenAmount).toSignificant(4, { groupSeparator: ',' })}
</Button>
)
}
Example #4
Source File: index.tsx From sybil-interface with GNU General Public License v3.0 | 6 votes |
export default function Web3Status() {
const { active, account } = useWeb3React()
const contextNetwork = useWeb3React(NetworkContextName)
const { ENSName } = useENSName(account ?? undefined)
const allTransactions = useAllTransactions()
const sortedRecentTransactions = useMemo(() => {
const txs = Object.values(allTransactions)
return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
}, [allTransactions])
const pending = sortedRecentTransactions.filter((tx) => !tx.receipt).map((tx) => tx.hash)
const confirmed = sortedRecentTransactions.filter((tx) => tx.receipt).map((tx) => tx.hash)
if (!contextNetwork.active && !active) {
return null
}
return <WalletModal ENSName={ENSName ?? undefined} pendingTransactions={pending} confirmedTransactions={confirmed} />
}
Example #5
Source File: App.tsx From ether-swr with MIT License | 6 votes |
EthBalance = () => {
const { account } = useWeb3React<Web3Provider>()
const { data: balance, mutate } = useEtherSWR(
['getBalance', account, 'latest'],
{
subscribe: [
{
name: 'block',
on: (event: any) => {
console.log('block', { event })
// on every block we check if Ether balance has changed by re-fetching
mutate(undefined, true)
}
}
]
}
)
if (!balance) {
return <div>...</div>
}
return <div>{parseFloat(formatEther(balance)).toPrecision(4)} Ξ</div>
}
Example #6
Source File: index.tsx From cheeseswap-interface with GNU General Public License v3.0 | 6 votes |
UnlockButton: React.FC<ButtonProps> = props => {
const TranslateString = useI18n()
const { account, activate, deactivate } = useWeb3React()
const handleLogin = (connectorId: ConnectorId) => {
if (connectorId === 'walletconnect') {
return activate(walletconnect)
}
return activate(injected)
}
const { onPresentConnectModal } = useWalletModal(handleLogin, deactivate, account as string)
return (
<Button onClick={onPresentConnectModal} {...props}>
{TranslateString(292, 'Unlock Wallet')}
</Button>
)
}
Example #7
Source File: AppWindowEthereum.tsx From dope-monorepo with GNU General Public License v3.0 | 6 votes |
AppWindowEthereum = ({ children, ...rest }: AppWindowProps) => {
const [showNetworkAlert, setShowNetworkAlert] = useState(false);
const { account, chainId } = useWeb3React();
useSwitchEthereum(chainId, account);
useEffect(() => {
const localNetworkAlert = localStorage.getItem('networkAlertEthereum');
if (localNetworkAlert !== 'true') {
setShowNetworkAlert(true);
}
}, []);
const onProperNetwork = useMemo(() => {
return !(account && chainId !== 1 && chainId !== 42 && showNetworkAlert);
}, [account, chainId, showNetworkAlert]);
return (
<AppWindow {...rest}>
{!onProperNetwork && <DialogSwitchNetwork networkName="Ethereum" />}
{onProperNetwork && children}
</AppWindow>
);
}
Example #8
Source File: index.tsx From dyp with Do What The F*ck You Want To Public License | 6 votes |
export default function Web3Status() {
const { active, account } = useWeb3React()
const contextNetwork = useWeb3React(NetworkContextName)
const { ENSName } = useENSName(account ?? undefined)
const allTransactions = useAllTransactions()
const sortedRecentTransactions = useMemo(() => {
const txs = Object.values(allTransactions)
return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
}, [allTransactions])
const pending = sortedRecentTransactions.filter(tx => !tx.receipt).map(tx => tx.hash)
const confirmed = sortedRecentTransactions.filter(tx => tx.receipt).map(tx => tx.hash)
if (!contextNetwork.active && !active) {
return null
}
return (
<>
<Web3StatusInner />
<WalletModal ENSName={ENSName ?? undefined} pendingTransactions={pending} confirmedTransactions={confirmed} />
</>
)
}
Example #9
Source File: index.tsx From glide-frontend with GNU General Public License v3.0 | 6 votes |
UserMenu = () => {
const { t } = useTranslation()
const { account } = useWeb3React()
const { logout } = useAuth()
const { balance, fetchStatus } = useGetBnbBalance()
// const { isInitialized, isLoading, profile } = useProfile()
const [onPresentWalletModal] = useModal(<WalletModal initialView={WalletView.WALLET_INFO} />)
const [onPresentTransactionModal] = useModal(<WalletModal initialView={WalletView.TRANSACTIONS} />)
// const hasProfile = isInitialized && !!profile
// const avatarSrc = profile && profile.nft ? `/images/nfts/${profile.nft.images.sm}` : undefined
const hasLowBnbBalance = fetchStatus === FetchStatus.SUCCESS && balance.lte(LOW_BNB_BALANCE)
if (!account) {
return <ConnectWalletButton scale="sm" />
}
return (
// <UIKitUserMenu account={account} avatarSrc={avatarSrc}>
<UIKitUserMenu account={account}>
<WalletUserMenuItem hasLowBnbBalance={hasLowBnbBalance} onPresentWalletModal={onPresentWalletModal} />
<UserMenuItem as="button" onClick={onPresentTransactionModal}>
{t('Transactions')}
</UserMenuItem>
<UserMenuDivider />
{/* <ProfileUserMenuItem isLoading={isLoading} hasProfile={hasProfile} /> */}
{/* <UserMenuDivider /> */}
<UserMenuItem as="button" onClick={logout}>
<Flex alignItems="center" justifyContent="space-between" width="100%">
{t('Disconnect')}
<LogoutIcon />
</Flex>
</UserMenuItem>
</UIKitUserMenu>
)
}
Example #10
Source File: PageRouter.tsx From dxvote with GNU Affero General Public License v3.0 | 5 votes |
PageRouter = observer(({ children }) => {
const {
context: {
notificationStore,
configStore,
etherscanService,
pinataService,
coingeckoService,
},
} = useContext();
const history = useHistory();
const location = useLocation();
const noLoading = ['/faq', '/config', '/forum', '/cache'];
const networkName = configStore.getActiveChainName();
const { active: providerActive } = useWeb3React();
useEffect(() => {
if (location.pathname == '/' && networkName) {
history.push(`/${networkName}/proposals`);
}
}, [networkName]);
// Start or auth services
pinataService.isAuthenticated();
etherscanService.isAuthenticated(networkName);
if (noLoading.indexOf(location.pathname) > -1) {
return <PageRouterWrapper>{children}</PageRouterWrapper>;
} else if (!providerActive) {
return (
<PageRouterWrapper>
<LoadingBox>
<div className="loader">
<PulsingIcon size={80} inactive={true} />
<div>Connect to a network to continue.</div>
</div>
</LoadingBox>
</PageRouterWrapper>
);
} else {
if (
!notificationStore.firstLoadComplete ||
notificationStore.globalLoadingState == GlobalLoadingState.ERROR
) {
const hasError =
notificationStore.globalLoadingState == GlobalLoadingState.ERROR;
return (
<PageRouterWrapper>
<LoadingBox>
<div className="loader">
{' '}
<PulsingIcon size={80} inactive={hasError} />
<div>{hasError ? 'Oops! Something broke.' : 'Loading'}</div>
<LoadingProgressText>
{notificationStore.globalMessage}
</LoadingProgressText>
</div>
</LoadingBox>
</PageRouterWrapper>
);
} else {
coingeckoService.loadPrices();
if (configStore.getLocalConfig().pinOnStart)
pinataService.updatePinList();
return <PageRouterWrapper> {children} </PageRouterWrapper>;
}
}
})
Example #11
Source File: index.tsx From cuiswap with GNU General Public License v3.0 | 5 votes |
export default function Web3ReactManager({ children }) {
const { t } = useTranslation()
const { active } = useWeb3React()
const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)
// try to eagerly connect to an injected provider, if it exists and has granted access already
const triedEager = useEagerConnect()
// after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
useEffect(() => {
if (triedEager && !networkActive && !networkError && !active) {
activateNetwork(network)
}
}, [triedEager, networkActive, networkError, activateNetwork, active])
// when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
useInactiveListener(!triedEager)
// handle delayed loader state
const [showLoader, setShowLoader] = useState(false)
useEffect(() => {
const timeout = setTimeout(() => {
setShowLoader(true)
}, 600)
return () => {
clearTimeout(timeout)
}
}, [])
// on page load, do nothing until we've tried to connect to the injected connector
if (!triedEager) {
return null
}
// if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
if (!active && networkError) {
return (
<MessageWrapper>
<Message>{t('unknownError')}</Message>
</MessageWrapper>
)
}
// if neither context is active, spin
if (!active && !networkActive) {
return showLoader ? (
<MessageWrapper>
<Loader />
</MessageWrapper>
) : null
}
return children
}
Example #12
Source File: TokenSelect.tsx From hypertext with GNU General Public License v3.0 | 5 votes |
function RemoteTokensData({ query }: { query: string }): JSX.Element {
const { chainId } = useWeb3React()
const [tokens] = useAllTokens()
const { data: remoteTokensCased } = useRemoteTokens(query, true)
const { data: remoteTokensLower } = useRemoteTokens(query.toLowerCase(), true)
const { data: remoteTokensUpper } = useRemoteTokens(query.toUpperCase(), true)
const remoteTokens = useMemo(
() => (remoteTokensCased || []).concat(remoteTokensLower || []).concat(remoteTokensUpper || []),
[remoteTokensCased, remoteTokensLower, remoteTokensUpper]
)
const remoteTokensFiltered = useMemo(
() =>
Array.from(new Set(remoteTokens.map((remoteToken) => remoteToken.address))) // get unique addresses
.filter((address) => !tokens.some((token) => token.address === address)) // filter out tokens already in our list
.map((address) => remoteTokens.find((remoteToken) => remoteToken.address === address)), // get the full remote tokens
[remoteTokens, tokens]
).sort((a, b) => {
const aExact = a?.symbol?.slice(0, query.length)?.toLowerCase() === query.toLowerCase()
const bExact = b?.symbol?.slice(0, query.length)?.toLowerCase() === query.toLowerCase()
if (aExact && !bExact) {
return -1
} else if (!aExact && bExact) {
return 1
} else {
return (a?.symbol?.toLowerCase() ?? 0) > (b?.symbol?.toLowerCase() ?? 0) ? 1 : -1
}
})
return remoteTokensFiltered.length === 0 ? (
<Text textAlign="center" pb="0.5rem">
No results
</Text>
) : (
<ComboboxList as={List}>
{remoteTokensFiltered.map((token) => {
const DUMMY = new Token(chainId as number, (token as Token).address, 18) // we don't know if it actually has 18 decimals
return (
<ComboboxOption as={ListItem} key={(token as Token).address} value={(token as Token).address}>
<Stack direction="row" align="center" p="0.5rem" shouldWrapChildren>
<TokenLogo token={DUMMY} size="1.5rem" />
<Stack direction="column" ml="1rem" spacing={0}>
<Text>{(token as Token).symbol}</Text>
<Text fontSize="1rem">{(token as Token).name}</Text>
</Stack>
</Stack>
</ComboboxOption>
)
})}
</ComboboxList>
)
}
Example #13
Source File: Web3ReactManager.tsx From interface-v2 with GNU General Public License v3.0 | 5 votes |
Web3ReactManager: React.FC<{ children: JSX.Element }> = ({
children,
}) => {
const { t } = useTranslation();
const classes = useStyles();
const { active } = useWeb3React();
const {
active: networkActive,
error: networkError,
activate: activateNetwork,
} = useWeb3React(GlobalConst.utils.NetworkContextName);
// try to eagerly connect to an injected provider, if it exists and has granted access already
const triedEager = useEagerConnect();
// after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
useEffect(() => {
if (triedEager && !networkActive && !networkError && !active) {
activateNetwork(network);
}
}, [triedEager, networkActive, networkError, activateNetwork, active]);
// when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
useInactiveListener(!triedEager);
// handle delayed loader state
const [showLoader, setShowLoader] = useState(false);
useEffect(() => {
const timeout = setTimeout(() => {
setShowLoader(true);
}, 600);
return () => {
clearTimeout(timeout);
};
}, []);
// on page load, do nothing until we've tried to connect to the injected connector
if (!triedEager) {
return null;
}
// if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
if (!active && networkError) {
return (
<Box className={classes.messageWrapper}>
<Typography className={classes.message}>{t('unknownError')}</Typography>
</Box>
);
}
// if neither context is active, spin
if (!active && !networkActive) {
return showLoader ? (
<Box className={classes.messageWrapper}>
<CircularProgress />
</Box>
) : null;
}
return children;
}
Example #14
Source File: index.tsx From sybil-interface with GNU General Public License v3.0 | 5 votes |
export default function Web3ReactManager({ children }: { children: JSX.Element }) {
const { t } = useTranslation()
const { active } = useWeb3React()
const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)
// try to eagerly connect to an injected provider, if it exists and has granted access already
const triedEager = useEagerConnect()
// after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
useEffect(() => {
if (triedEager && !networkActive && !networkError && !active) {
activateNetwork(network)
}
}, [triedEager, networkActive, networkError, activateNetwork, active])
// when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
useInactiveListener(!triedEager)
// handle delayed loader state
const [showLoader, setShowLoader] = useState(false)
useEffect(() => {
const timeout = setTimeout(() => {
setShowLoader(true)
}, 600)
return () => {
clearTimeout(timeout)
}
}, [])
// on page load, do nothing until we've tried to connect to the injected connector
if (!triedEager) {
return null
}
// if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
if (!active && networkError) {
return (
<MessageWrapper>
<Message>{t('unknownError')}</Message>
</MessageWrapper>
)
}
// if neither context is active, spin
if (!active && !networkActive) {
return showLoader ? (
<MessageWrapper>
<Loader />
</MessageWrapper>
) : null
}
return children
}
Example #15
Source File: App.tsx From ether-swr with MIT License | 5 votes |
TokenBalance = ({
symbol,
address,
decimals
}: {
symbol: string
address: string
decimals: number
}) => {
const { account } = useWeb3React<Web3Provider>()
const { data: balance, mutate } = useEtherSWR(
[address, 'balanceOf', account],
{
subscribe: [
// A filter from anyone to me
{
name: 'Transfer',
topics: [null, account],
on: (
state: BigNumber,
fromAddress: string,
toAddress: string,
amount: BigNumber,
event: any
) => {
console.log('receive', { event })
const update = state.add(amount)
mutate(update, false) // optimistic update skip re-fetch
}
},
// A filter from me to anyone
{
name: 'Transfer',
topics: [account, null],
on: (
state: BigNumber,
fromAddress: string,
toAddress: string,
amount: BigNumber,
event: any
) => {
console.log('send', { event })
const update = state.sub(amount)
mutate(update, false) // optimistic update skip re-fetch
}
}
]
}
)
if (!balance) {
return <div>...</div>
}
return (
<div>
{parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}
</div>
)
}
Example #16
Source File: index.tsx From cheeseswap-interface with GNU General Public License v3.0 | 5 votes |
export default function Web3ReactManager({ children }: { children: JSX.Element }) {
const { t } = useTranslation()
const { active } = useWeb3React()
const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)
// try to eagerly connect to an injected provider, if it exists and has granted access already
const triedEager = useEagerConnect()
// after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
useEffect(() => {
if (triedEager && !networkActive && !networkError && !active) {
activateNetwork(network)
}
}, [triedEager, networkActive, networkError, activateNetwork, active])
// when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
useInactiveListener(!triedEager)
// handle delayed loader state
const [showLoader, setShowLoader] = useState(false)
useEffect(() => {
const timeout = setTimeout(() => {
setShowLoader(true)
}, 600)
return () => {
clearTimeout(timeout)
}
}, [])
// on page load, do nothing until we've tried to connect to the injected connector
if (!triedEager) {
return null
}
// if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
if (!active && networkError) {
return (
<MessageWrapper>
<Message>{t('unknownError')}</Message>
</MessageWrapper>
)
}
// if neither context is active, spin
if (!active && !networkActive) {
return showLoader ? (
<MessageWrapper>
<Loader />
</MessageWrapper>
) : null
}
return children
}