hooks/Tokens#useToken TypeScript Examples
The following examples show how to use
hooks/Tokens#useToken.
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: CurrencySearch.tsx From interface-v2 with GNU General Public License v3.0 | 4 votes |
CurrencySearch: React.FC<CurrencySearchProps> = ({
selectedCurrency,
onCurrencySelect,
otherSelectedCurrency,
showCommonBases,
onDismiss,
isOpen,
}) => {
const classes = useStyles();
const { t } = useTranslation();
const { account, chainId } = useActiveWeb3React();
const dispatch = useDispatch<AppDispatch>();
const fixedList = useRef<FixedSizeList>();
const handleInput = useCallback((input: string) => {
const checksummedInput = isAddress(input);
setSearchQuery(checksummedInput || input);
fixedList.current?.scrollTo(0);
}, []);
const [searchQuery, setSearchQuery] = useState<string>('');
const [searchQueryInput, setSearchQueryInput] = useDebouncedChangeHandler(
searchQuery,
handleInput,
);
const allTokens = useAllTokens();
// if they input an address, use it
const isAddressSearch = isAddress(searchQuery);
const searchToken = useToken(searchQuery);
useEffect(() => {
if (isAddressSearch) {
ReactGA.event({
category: 'Currency Select',
action: 'Search by address',
label: isAddressSearch,
});
}
}, [isAddressSearch]);
const showETH: boolean = useMemo(() => {
const s = searchQuery.toLowerCase().trim();
return s === '' || s === 'e' || s === 'et' || s === 'eth';
}, [searchQuery]);
const tokenComparator = useTokenComparator(false);
const filteredTokens: Token[] = useMemo(() => {
if (isAddressSearch) return searchToken ? [searchToken] : [];
return filterTokens(Object.values(allTokens), searchQuery);
}, [isAddressSearch, searchToken, allTokens, searchQuery]);
const filteredSortedTokens: Token[] = useMemo(() => {
if (searchToken) return [searchToken];
const sorted = filteredTokens.sort(tokenComparator);
const symbolMatch = searchQuery
.toLowerCase()
.split(/\s+/)
.filter((s) => s.length > 0);
if (symbolMatch.length > 1) return sorted;
return [
...(searchToken ? [searchToken] : []),
// sort any exact symbol matches first
...sorted.filter(
(token) => token.symbol?.toLowerCase() === symbolMatch[0],
),
...sorted.filter(
(token) => token.symbol?.toLowerCase() !== symbolMatch[0],
),
];
}, [filteredTokens, searchQuery, searchToken, tokenComparator]);
const handleCurrencySelect = useCallback(
(currency: Currency) => {
onCurrencySelect(currency);
onDismiss();
},
[onDismiss, onCurrencySelect],
);
// clear the input on open
useEffect(() => {
if (isOpen) setSearchQuery('');
}, [isOpen]);
const handleEnter = useCallback(
(e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
const s = searchQuery.toLowerCase().trim();
if (s === 'eth') {
handleCurrencySelect(ETHER);
} else if (filteredSortedTokens.length > 0) {
if (
filteredSortedTokens[0].symbol?.toLowerCase() ===
searchQuery.trim().toLowerCase() ||
filteredSortedTokens.length === 1
) {
handleCurrencySelect(filteredSortedTokens[0]);
}
}
}
},
[filteredSortedTokens, handleCurrencySelect, searchQuery],
);
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>();
let selectedListInfo = useSelectedListInfo();
if (selectedListInfo.current === null) {
dispatch(selectList(GlobalConst.utils.DEFAULT_TOKEN_LIST_URL));
}
selectedListInfo = useSelectedListInfo();
return (
<Box className={classes.wrapper}>
<Box className={classes.header}>
<Typography variant='subtitle2'>Select a token</Typography>
<CloseIcon onClick={onDismiss} />
</Box>
<Box className={classes.searchInputWrapper}>
<SearchIcon />
<input
type='text'
placeholder={t('tokenSearchPlaceholder')}
value={searchQueryInput}
ref={inputRef as RefObject<HTMLInputElement>}
onChange={(e) => setSearchQueryInput(e.target.value)}
onKeyDown={handleEnter}
/>
</Box>
{showCommonBases && (
<CommonBases
chainId={chainId}
onSelect={handleCurrencySelect}
selectedCurrency={selectedCurrency}
/>
)}
<Divider />
<Box flex={1}>
<AutoSizer disableWidth>
{({ height }) => (
<CurrencyList
showETH={showETH}
height={height}
currencies={filteredSortedTokens}
onCurrencySelect={handleCurrencySelect}
otherCurrency={otherSelectedCurrency}
selectedCurrency={selectedCurrency}
fixedListRef={fixedList}
/>
)}
</AutoSizer>
</Box>
<Box className={classes.footer} />
</Box>
);
}
Example #2
Source File: ManageTokens.tsx From glide-frontend with GNU General Public License v3.0 | 4 votes |
export default function ManageTokens({
setModalView,
setImportToken,
}: {
setModalView: (view: CurrencyModalView) => void
setImportToken: (token: Token) => void
}) {
const { chainId } = useActiveWeb3React()
const { t } = useTranslation()
const [searchQuery, setSearchQuery] = useState<string>('')
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => {
const input = event.target.value
const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input)
}, [])
// if they input an address, use it
const searchToken = useToken(searchQuery)
// all tokens for local lisr
const userAddedTokens: Token[] = useUserAddedTokens()
const removeToken = useRemoveUserAddedToken()
const handleRemoveAll = useCallback(() => {
if (chainId && userAddedTokens) {
userAddedTokens.map((token) => {
return removeToken(chainId, token.address)
})
}
}, [removeToken, userAddedTokens, chainId])
const tokenList = useMemo(() => {
return (
chainId &&
userAddedTokens.map((token) => (
<RowBetween key={token.address} width="100%">
<RowFixed>
<CurrencyLogo currency={token} size="20px" />
<Link external href={getBscScanLink(token.address, 'address', chainId)} color="textSubtle" ml="10px">
{token.symbol}
</Link>
</RowFixed>
<RowFixed>
<IconButton variant="text" onClick={() => removeToken(chainId, token.address)}>
<CloseIcon />
</IconButton>
<LinkExternal href={getBscScanLink(token.address, 'address', chainId)} />
</RowFixed>
</RowBetween>
))
)
}, [userAddedTokens, chainId, removeToken])
const isAddressValid = searchQuery === '' || isAddress(searchQuery)
return (
<Wrapper>
<Column style={{ width: '100%', flex: '1 1' }}>
<AutoColumn gap="14px">
<Row>
<Input
id="token-search-input"
scale="lg"
placeholder="0x0000"
value={searchQuery}
autoComplete="off"
ref={inputRef as RefObject<HTMLInputElement>}
onChange={handleInput}
isWarning={!isAddressValid}
/>
</Row>
{!isAddressValid && <Text color="failure">{t('Enter valid token address')}</Text>}
{searchToken && (
<ImportRow
token={searchToken}
showImportView={() => setModalView(CurrencyModalView.importToken)}
setImportToken={setImportToken}
style={{ height: 'fit-content' }}
/>
)}
</AutoColumn>
{tokenList}
<Footer>
<Text bold color="textSubtle">
{userAddedTokens?.length} {userAddedTokens.length === 1 ? t('Custom Token') : t('Custom Tokens')}
</Text>
{userAddedTokens.length > 0 && (
<Button variant="tertiary" onClick={handleRemoveAll}>
{t('Clear all')}
</Button>
)}
</Footer>
</Column>
</Wrapper>
)
}
Example #3
Source File: ManageTokens.tsx From glide-frontend with GNU General Public License v3.0 | 4 votes |
export default function ManageTokens({
setModalView,
setImportToken,
}: {
setModalView: (view: CurrencyModalView) => void
setImportToken: (token: Token) => void
}) {
const { chainId } = useActiveWeb3React()
const { t } = useTranslation()
const [searchQuery, setSearchQuery] = useState<string>('')
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => {
const input = event.target.value
const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input)
}, [])
// if they input an address, use it
const searchToken = useToken(searchQuery)
// all tokens for local lisr
const userAddedTokens: Token[] = useUserAddedTokens()
const removeToken = useRemoveUserAddedToken()
const handleRemoveAll = useCallback(() => {
if (chainId && userAddedTokens) {
userAddedTokens.map((token) => {
return removeToken(chainId, token.address)
})
}
}, [removeToken, userAddedTokens, chainId])
const tokenList = useMemo(() => {
return (
chainId &&
userAddedTokens.map((token) => (
<RowBetween key={token.address} width="100%">
<RowFixed>
<CurrencyLogo currency={token} size="20px" />
<Link external href={getBscScanLink(token.address, 'address', chainId)} color="textSubtle" ml="10px">
{token.symbol}
</Link>
</RowFixed>
<RowFixed>
<IconButton variant="text" onClick={() => removeToken(chainId, token.address)}>
<CloseIcon />
</IconButton>
<LinkExternal href={getBscScanLink(token.address, 'address', chainId)} />
</RowFixed>
</RowBetween>
))
)
}, [userAddedTokens, chainId, removeToken])
const isAddressValid = searchQuery === '' || isAddress(searchQuery)
return (
<Wrapper>
<Column style={{ width: '100%', flex: '1 1' }}>
<AutoColumn gap="14px">
<Row>
<Input
id="token-search-input"
scale="lg"
placeholder="0x0000"
value={searchQuery}
autoComplete="off"
ref={inputRef as RefObject<HTMLInputElement>}
onChange={handleInput}
isWarning={!isAddressValid}
/>
</Row>
{!isAddressValid && <Text color="failure">{t('Enter valid token address')}</Text>}
{searchToken && (
<ImportRow
token={searchToken}
showImportView={() => setModalView(CurrencyModalView.importToken)}
setImportToken={setImportToken}
style={{ height: 'fit-content' }}
/>
)}
</AutoColumn>
{tokenList}
<Footer>
<Text bold color="textSubtle">
{userAddedTokens?.length} {userAddedTokens.length === 1 ? t('Custom Token') : t('Custom Tokens')}
</Text>
{userAddedTokens.length > 0 && (
<Button variant="tertiary" onClick={handleRemoveAll}>
{t('Clear all')}
</Button>
)}
</Footer>
</Column>
</Wrapper>
)
}
Example #4
Source File: ManageTokens.tsx From forward.swaps with GNU General Public License v3.0 | 4 votes |
export default function ManageTokens({
setModalView,
setImportToken
}: {
setModalView: (view: CurrencyModalView) => void
setImportToken: (token: Token) => void
}) {
const { chainId } = useActiveWeb3React()
const [searchQuery, setSearchQuery] = useState<string>('')
const theme = useTheme()
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback(event => {
const input = event.target.value
const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input)
}, [])
// if they input an address, use it
const isAddressSearch = isAddress(searchQuery)
const searchToken = useToken(searchQuery)
// all tokens for local lisr
const userAddedTokens: Token[] = useUserAddedTokens()
const removeToken = useRemoveUserAddedToken()
const handleRemoveAll = useCallback(() => {
if (chainId && userAddedTokens) {
userAddedTokens.map(token => {
return removeToken(chainId, token.address)
})
}
}, [removeToken, userAddedTokens, chainId])
const tokenList = useMemo(() => {
return (
chainId &&
userAddedTokens.map(token => (
<RowBetween key={token.address} width="100%">
<RowFixed>
<CurrencyLogo currency={token} size={'20px'} />
<ExternalLink href={getEtherscanLink(chainId, token.address, 'address')}>
<TYPE.main ml={'10px'} fontWeight={600}>
{token.symbol}
</TYPE.main>
</ExternalLink>
</RowFixed>
<RowFixed>
<TrashIcon onClick={() => removeToken(chainId, token.address)} />
<ExternalLinkIcon href={getEtherscanLink(chainId, token.address, 'address')} />
</RowFixed>
</RowBetween>
))
)
}, [userAddedTokens, chainId, removeToken])
return (
<Wrapper>
<Column style={{ width: '100%', flex: '1 1' }}>
<PaddedColumn gap="14px">
<Row>
<SearchInput
type="text"
id="token-search-input"
placeholder={'0x0000'}
value={searchQuery}
autoComplete="off"
ref={inputRef as RefObject<HTMLInputElement>}
onChange={handleInput}
/>
</Row>
{searchQuery !== '' && !isAddressSearch && <TYPE.error error={true}>Enter valid token address</TYPE.error>}
{searchToken && (
<Card backgroundColor={theme.bg2} padding="10px 0">
<ImportRow
token={searchToken}
showImportView={() => setModalView(CurrencyModalView.importToken)}
setImportToken={setImportToken}
style={{ height: 'fit-content' }}
/>
</Card>
)}
</PaddedColumn>
<Separator />
<PaddedColumn gap="lg">
<RowBetween>
<TYPE.main fontWeight={600}>
{userAddedTokens?.length} Custom {userAddedTokens.length === 1 ? 'Token' : 'Tokens'}
</TYPE.main>
{userAddedTokens.length > 0 && (
<ButtonText onClick={handleRemoveAll}>
<TYPE.blue>Clear all</TYPE.blue>
</ButtonText>
)}
</RowBetween>
{tokenList}
</PaddedColumn>
</Column>
<Footer>
<TYPE.darkGray>Tip: Custom tokens are stored locally in your browser</TYPE.darkGray>
</Footer>
</Wrapper>
)
}
Example #5
Source File: ManageTokens.tsx From vvs-ui with GNU General Public License v3.0 | 4 votes |
export default function ManageTokens({
setModalView,
setImportToken,
}: {
setModalView: (view: CurrencyModalView) => void
setImportToken: (token: Token) => void
}) {
const { chainId } = useActiveWeb3React()
const { t } = useTranslation()
const [searchQuery, setSearchQuery] = useState<string>('')
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => {
const input = event.target.value
const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input)
}, [])
// if they input an address, use it
const searchToken = useToken(searchQuery)
// all tokens for local list
const userAddedTokens: Token[] = useUserAddedTokens()
const removeToken = useRemoveUserAddedToken()
const handleRemoveAll = useCallback(() => {
if (chainId && userAddedTokens) {
userAddedTokens.map((token) => {
return removeToken(chainId, token.address)
})
}
}, [removeToken, userAddedTokens, chainId])
const tokenList = useMemo(() => {
return (
chainId &&
userAddedTokens.map((token) => (
<RowBetween key={token.address} width="100%">
<RowFixed>
<CurrencyLogo currency={token} size="20px" />
<Link external href={getExplorerLink(token.address, 'address', chainId)} color="textSubtle" ml="10px">
{token.symbol}
</Link>
</RowFixed>
<RowFixed>
<IconButton variant="text" onClick={() => removeToken(chainId, token.address)}>
<CloseIcon />
</IconButton>
<LinkExternal href={getExplorerLink(token.address, 'address', chainId)} />
</RowFixed>
</RowBetween>
))
)
}, [userAddedTokens, chainId, removeToken])
const isAddressValid = searchQuery === '' || isAddress(searchQuery)
return (
<Wrapper>
<Column style={{ width: '100%', flex: '1 1' }}>
<AutoColumn gap="14px">
<Row>
<Input
id="token-search-input"
scale="lg"
placeholder="0x0000"
value={searchQuery}
autoComplete="off"
ref={inputRef as RefObject<HTMLInputElement>}
onChange={handleInput}
isWarning={!isAddressValid}
/>
</Row>
{!isAddressValid && <Text color="failure">{t('Enter valid token address')}</Text>}
{searchToken && (
<ImportRow
token={searchToken}
showImportView={() => setModalView(CurrencyModalView.importToken)}
setImportToken={setImportToken}
style={{ height: 'fit-content' }}
/>
)}
</AutoColumn>
{tokenList}
<Footer>
<Text bold color="textSubtle">
{userAddedTokens?.length} {userAddedTokens.length === 1 ? t('Custom Token') : t('Custom Tokens')}
</Text>
{userAddedTokens.length > 0 && (
<Button variant="tertiary" onClick={handleRemoveAll}>
{t('Clear all')}
</Button>
)}
</Footer>
</Column>
</Wrapper>
)
}