Skip to content

Commit

Permalink
Move useCoinPrices to kit package
Browse files Browse the repository at this point in the history
  • Loading branch information
corbanbrook committed Apr 30, 2024
1 parent 91cb293 commit 4f692ed
Show file tree
Hide file tree
Showing 13 changed files with 69 additions and 114 deletions.
24 changes: 0 additions & 24 deletions packages/checkout/src/api/data.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Token, TokenPrice } from '@0xsequence/api'
import { getNetworkConfigAndClients } from '@0xsequence/kit'
import { TokenBalance, ContractType } from '@0xsequence/indexer'
import { GetContractInfoArgs, ContractInfo, TokenMetadata } from '@0xsequence/metadata'
import { ethers } from 'ethers'

import { getPaperNetworkName } from '../utils'
Expand Down Expand Up @@ -107,28 +105,6 @@ export const fetchCollectionBalance = async ({
}
}

export interface GetCoinPricesArgs {
tokens: Token[]
}

export const getCoinPrices = async ({ tokens }: GetCoinPricesArgs): Promise<TokenPrice[] | undefined> => {
try {
if (tokens.length === 0) return []
const chainId = tokens[0].chainId

const { apiClient } = getNetworkConfigAndClients(chainId)

const res = await apiClient.getCoinPrices({
tokens
})

return res?.tokenPrices || []
} catch (e) {
console.error(e)
return
}
}

export interface FetchPaperSecretArgs {
chainId: number
email: string
Expand Down
19 changes: 1 addition & 18 deletions packages/checkout/src/hooks/data.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import { useQuery, UseQueryResult } from '@tanstack/react-query'
import { TokenPrice } from '@0xsequence/api'
import { TokenBalance } from '@0xsequence/indexer'

import {
fetchBalances,
GetTokenBalancesArgs,
fetchCollectionBalance,
GetCollectionBalanceArgs,
getCoinPrices,
GetCoinPricesArgs
} from '../api/data'
import { fetchBalances, GetTokenBalancesArgs, fetchCollectionBalance, GetCollectionBalanceArgs } from '../api/data'

export const time = {
oneSecond: 1 * 1000,
Expand All @@ -34,12 +26,3 @@ export const useCollectionBalance = (args: GetCollectionBalanceArgs) =>
staleTime: 10 * time.oneMinute,
enabled: !!args.chainId && !!args.accountAddress && !!args.collectionAddress
})

export const useCoinPrices = (args: GetCoinPricesArgs): UseQueryResult<TokenPrice> =>
useQuery({
queryKey: ['coinPrices', args],
queryFn: () => getCoinPrices(args),
retry: true,
staleTime: 1 * time.oneMinute,
enabled: args.tokens.length > 0
})
23 changes: 16 additions & 7 deletions packages/kit/src/hooks/data.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GetCoinPricesArgs, GetExchangeRateArgs } from '@0xsequence/api'
import { GetCoinPricesArgs, GetExchangeRateArgs, SequenceAPIClient, Token } from '@0xsequence/api'
import { useQuery } from '@tanstack/react-query'

import { useMetadataClient } from './useMetadataClient'
Expand All @@ -25,29 +25,38 @@ export const useExchangeRate = (toCurrency: string) => {

return res.exchangeRate.value
},
initialData: 1,
retry: true,
staleTime: time.oneMinute * 10
})
}

export const useCoinPrices = (args: GetCoinPricesArgs) => {
// const getCoinPrices = async (apiClient: SequenceAPIClient, tokens: Token[]) => {
// if (args.tokens.length === 0) {
// return []
// }

// const res = await apiClient.getCoinPrices(args)

// return res?.tokenPrices || []
// }

export const useCoinPrices = (tokens: Token[]) => {
const apiClient = useAPIClient()

return useQuery({
queryKey: ['coinPrices', args],
queryKey: ['coinPrices', tokens],
queryFn: async () => {
if (args.tokens.length === 0) {
if (tokens.length === 0) {
return []
}

const res = await apiClient.getCoinPrices(args)
const res = await apiClient.getCoinPrices({ tokens })

return res?.tokenPrices || []
},
retry: true,
staleTime: time.oneMinute,
enabled: args.tokens.length > 0
enabled: tokens.length > 0
})
}

Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/utils/genericContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useContext, createContext } from 'react'

// https://medium.com/@rivoltafilippo/typing-react-context-to-avoid-an-undefined-default-value-2c7c5a7d5947

export const createGenericContext = <T,>() => {
export const createGenericContext = <T>() => {
// Create a context with a generic parameter or undefined
const genericContext = createContext<T | undefined>(undefined)

Expand Down
11 changes: 0 additions & 11 deletions packages/wallet/src/hooks/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import {
GetTokenBalancesArgs,
fetchCollectionBalance,
GetCollectionBalanceArgs,
getCoinPrices,
GetCoinPricesArgs,
fetchBalancesAssetsSummary,
getNativeToken,
getTokenBalances,
Expand Down Expand Up @@ -56,15 +54,6 @@ export const useCollectionBalance = (args: GetCollectionBalanceArgs) =>
enabled: !!args.chainId && !!args.accountAddress && !!args.collectionAddress
})

export const useCoinPrices = ({ disabled, ...args }: GetCoinPricesArgs & { disabled?: boolean }) =>
useQuery({
queryKey: ['coinPrices', args],
queryFn: () => getCoinPrices(args),
retry: true,
staleTime: time.oneSecond * 30,
enabled: args.tokens.length > 0 && !disabled
})

export const useBalancesAssetsSummary = (args: FetchBalancesAssetsArgs, options: GetTokenBalancesOptions) =>
useQuery({
queryKey: ['balancesAssetsSummary', args, options],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import React from 'react'
import { TokenPrice } from '@0xsequence/api'
import { ethers } from 'ethers'
import { Transaction, TxnTransfer, TxnTransferType } from '@0xsequence/indexer'
import { getNativeTokenInfoByChainId, useExchangeRate } from '@0xsequence/kit'
import { getNativeTokenInfoByChainId, useCoinPrices, useExchangeRate } from '@0xsequence/kit'
import { ArrowRightIcon, Box, Text, Image, SendIcon, ReceiveIcon, TransactionIcon, vars } from '@0xsequence/design-system'
import dayjs from 'dayjs'
import { useConfig } from 'wagmi'

import * as sharedStyles from '../../shared/styles.css'
import { Skeleton } from '../../shared/Skeleton'
import { useCoinPrices, useSettings, useNavigation } from '../../hooks'
import { useSettings, useNavigation } from '../../hooks'
import { formatDisplay, compareAddress } from '../../utils'

interface TransactionHistoryItemProps {
Expand Down Expand Up @@ -39,12 +39,12 @@ export const TransactionHistoryItem = ({ transaction }: TransactionHistoryItemPr
}
})

const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices({
tokens: tokenContractAddresses.map(contractAddress => ({
const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices(
tokenContractAddresses.map(contractAddress => ({
contractAddress,
chainId: transaction.chainId
}))
})
)

const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol)

Expand Down
2 changes: 1 addition & 1 deletion packages/wallet/src/utils/genericContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createContext, useContext } from 'react'

// https://medium.com/@rivoltafilippo/typing-react-context-to-avoid-an-undefined-default-value-2c7c5a7d5947

export const createGenericContext = <T,>() => {
export const createGenericContext = <T>() => {
// Create a context with a generic parameter or undefined
const genericContext = createContext<T | undefined>(undefined)

Expand Down
20 changes: 9 additions & 11 deletions packages/wallet/src/views/CoinDetails/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react'
import { ethers } from 'ethers'
import { Box, Button, Image, SendIcon, Text, vars } from '@0xsequence/design-system'
import { getNativeTokenInfoByChainId, useExchangeRate } from '@0xsequence/kit'
import { Box, Button, Image, SendIcon, Text } from '@0xsequence/design-system'
import { getNativeTokenInfoByChainId, useExchangeRate, useCoinPrices } from '@0xsequence/kit'

import { useAccount, useConfig } from 'wagmi'

Expand All @@ -10,7 +10,7 @@ import { CoinDetailsSkeleton } from './Skeleton'
import { InfiniteScroll } from '../../shared/InfiniteScroll'
import { NetworkBadge } from '../../shared/NetworkBadge'
import { TransactionHistoryList } from '../../shared/TransactionHistoryList'
import { useCoinBalance, useSettings, useCoinPrices, useTransactionHistory, useNavigation } from '../../hooks'
import { useCoinBalance, useSettings, useTransactionHistory, useNavigation } from '../../hooks'
import { HEADER_HEIGHT } from '../../constants'
import { compareAddress, computeBalanceFiat, formatDisplay, flattenPaginatedTransactionHistory } from '../../utils'
import { useScrollbarWidth } from '../../hooks/useScrollbarWidth'
Expand Down Expand Up @@ -51,14 +51,12 @@ export const CoinDetails = ({ contractAddress, chainId }: CoinDetailsProps) => {
{ hideUnlistedTokens }
)

const { data: dataCoinPrices, isPending: isPendingCoinPrices } = useCoinPrices({
tokens: [
{
chainId,
contractAddress
}
]
})
const { data: dataCoinPrices, isPending: isPendingCoinPrices } = useCoinPrices([
{
chainId,
contractAddress
}
])

const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { TokenBalance } from '@0xsequence/indexer'

import { CoinTileContent } from './CoinTileContent'

import { getNativeTokenInfoByChainId, useContractInfo, useExchangeRate } from '@0xsequence/kit'
import { getNativeTokenInfoByChainId, useContractInfo, useExchangeRate, useCoinPrices } from '@0xsequence/kit'

import { computeBalanceFiat, formatDisplay, getPercentagePriceChange, compareAddress } from '../../../../../utils'

import { useCoinPrices, useSettings } from '../../../../../hooks'
import { useSettings } from '../../../../../hooks'

interface CoinTileProps {
balance: TokenBalance
Expand All @@ -22,14 +22,12 @@ export const CoinTile = ({ balance }: CoinTileProps) => {
const isNativeToken = compareAddress(balance.contractAddress, ethers.constants.AddressZero)
const nativeTokenInfo = getNativeTokenInfoByChainId(balance.chainId, chains)

const { data: dataCoinPrices = [], isPending: isPendingCoinPrice } = useCoinPrices({
tokens: [
{
chainId: balance.chainId,
contractAddress: balance.contractAddress
}
]
})
const { data: dataCoinPrices = [], isPending: isPendingCoinPrice } = useCoinPrices([
{
chainId: balance.chainId,
contractAddress: balance.contractAddress
}
])

const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol)

Expand Down
10 changes: 5 additions & 5 deletions packages/wallet/src/views/Search/SearchWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import React, { useState } from 'react'
import { ethers } from 'ethers'
import { Box, SearchIcon, Text, TextInput, vars } from '@0xsequence/design-system'
import { getNativeTokenInfoByChainId, useExchangeRate } from '@0xsequence/kit'
import { getNativeTokenInfoByChainId, useExchangeRate, useCoinPrices } from '@0xsequence/kit'
import Fuse from 'fuse.js'
import { useAccount, useConfig } from 'wagmi'

import { BalanceItem } from './components/BalanceItem'
import { WalletLink } from './components/WalletLink'

import { Skeleton } from '../../shared/Skeleton'
import { useBalances, useCoinPrices, useSettings } from '../../hooks'
import { useBalances, useSettings } from '../../hooks'
import { compareAddress, computeBalanceFiat } from '../../utils'
import { useScrollbarWidth } from '../../hooks/useScrollbarWidth'

Expand All @@ -33,12 +33,12 @@ export const SearchWallet = () => {
b => b.contractType === 'ERC20' || compareAddress(b.contractAddress, ethers.constants.AddressZero)
) || []

const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices({
tokens: coinBalancesUnordered.map(token => ({
const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices(
coinBalancesUnordered.map(token => ({
chainId: token.chainId,
contractAddress: token.contractAddress
}))
})
)

const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol)

Expand Down
12 changes: 6 additions & 6 deletions packages/wallet/src/views/Search/SearchWalletViewAll.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React, { useState, useEffect } from 'react'
import { ethers } from 'ethers'
import { Box, SearchIcon, TabsContent, TabsHeader, TabsRoot, Text, TextInput, vars } from '@0xsequence/design-system'
import { getNativeTokenInfoByChainId, useExchangeRate } from '@0xsequence/kit'
import { Box, SearchIcon, TabsContent, TabsHeader, TabsRoot, Text, TextInput } from '@0xsequence/design-system'
import { getNativeTokenInfoByChainId, useExchangeRate, useCoinPrices } from '@0xsequence/kit'
import { BalanceItem } from './components/BalanceItem'
import Fuse from 'fuse.js'
import { useAccount, useConfig } from 'wagmi'

import { Skeleton } from '../../shared/Skeleton'
import { useBalances, useCoinPrices, useSettings } from '../../hooks'
import { useBalances, useSettings } from '../../hooks'
import { compareAddress, computeBalanceFiat } from '../../utils'
import { useScrollbarWidth } from '../../hooks/useScrollbarWidth'

Expand Down Expand Up @@ -41,12 +41,12 @@ export const SearchWalletViewAll = ({ defaultTab }: SearchWalletViewAllProps) =>
b => b.contractType === 'ERC20' || compareAddress(b.contractAddress, ethers.constants.AddressZero)
) || []

const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices({
tokens: coinBalancesUnordered.map(token => ({
const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices(
coinBalancesUnordered.map(token => ({
chainId: token.chainId,
contractAddress: token.contractAddress
}))
})
)

const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol)

Expand Down
24 changes: 14 additions & 10 deletions packages/wallet/src/views/SendCoin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,19 @@ import {
vars,
Spinner
} from '@0xsequence/design-system'
import { getNativeTokenInfoByChainId, useAnalyticsContext, ExtendedConnector, useExchangeRate } from '@0xsequence/kit'
import {
getNativeTokenInfoByChainId,
useAnalyticsContext,
ExtendedConnector,
useExchangeRate,
useCoinPrices
} from '@0xsequence/kit'
import { TokenBalance } from '@0xsequence/indexer'
import { useAccount, useChainId, useSwitchChain, useConfig, useSendTransaction } from 'wagmi'

import { SendItemInfo } from '../shared/SendItemInfo'
import { ERC_20_ABI, HEADER_HEIGHT } from '../constants'
import { useBalances, useCoinPrices, useSettings, useOpenWalletModal, useNavigation } from '../hooks'
import { useBalances, useSettings, useOpenWalletModal, useNavigation } from '../hooks'
import { compareAddress, computeBalanceFiat, limitDecimals, isEthAddress, truncateAtMiddle } from '../utils'
import * as sharedStyles from '../shared/styles.css'

Expand Down Expand Up @@ -56,14 +62,12 @@ export const SendCoin = ({ chainId, contractAddress }: SendCoinProps) => {
)
const nativeTokenInfo = getNativeTokenInfoByChainId(chainId, chains)
const tokenBalance = (balances as TokenBalance[]).find(b => b.contractAddress === contractAddress)
const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices({
tokens: [
{
chainId,
contractAddress
}
]
})
const { data: coinPrices = [], isPending: isPendingCoinPrices } = useCoinPrices([
{
chainId,
contractAddress
}
])

const { data: conversionRate = 1, isPending: isPendingConversionRate } = useExchangeRate(fiatCurrency.symbol)

Expand Down
Loading

0 comments on commit 4f692ed

Please sign in to comment.