Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch token prices & history using new Explorer BE endpoints #109

Closed
wants to merge 13 commits into from
Closed
5 changes: 5 additions & 0 deletions .changeset/young-zoos-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'alephium-desktop-wallet': patch
---

Fetch token prices & ALPH history using new Explorer BE endpoints
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/bg-BG/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Използване на максимална сума",
"Use optional passphrase": "Use optional passphrase",
"Useful for miners or DeFi use.": "Полезно за копачи или DeFi употреба.",
"Value today": "Value today",
"Value today (ALPH)": "Value today (ALPH)",
nop33 marked this conversation as resolved.
Show resolved Hide resolved
"Version": "Версия",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Налична е версия {{ newVersion }}. Кликнете върху \"Актуализиране\" за да избегнете проблеми с портфейла.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/de-DE/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Maximalbetrag verwenden",
"Use optional passphrase": "Optionale Passphrase verwenden",
"Useful for miners or DeFi use.": "Nützlich für Miner oder DeFi.",
"Value today": "Value today",
"Value today (ALPH)": "Value today (ALPH)",
"Version": "Version",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Version {{ newVersion }} ist verfügbar. Bitte laden Sie sie herunter und installieren Sie diese, um Probleme mit der Wallet zu vermeiden.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Version {{ newVersion }} ist verfügbar. Bitte laden Sie sie herunter und installieren Sie sie, um Probleme mit der Brieftasche zu vermeiden.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/en-US/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@
"Use max amount": "Use max amount",
"Use optional passphrase": "Use optional passphrase",
"Useful for miners or DeFi use.": "Useful for miners or DeFi use.",
"Value today": "Value today",
"Value today (ALPH)": "Value today (ALPH)",
"Version": "Version",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/es-ES/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Utilizar la cantidad máxima",
"Use optional passphrase": "Use optional passphrase",
"Useful for miners or DeFi use.": "Útil para mineros o uso DeFi.",
"Value today": "Value today",
"Value today (ALPH)": "Value today (ALPH)",
"Version": "Versión",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "La versión {{ newVersion }} está disponible. Haga clic en \"Actualizar\" para evitar problemas con la billetera.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/fr-FR/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Utiliser le montant max",
"Use optional passphrase": "Utiliser la phrase de passe optionnelle",
"Useful for miners or DeFi use.": "Utile pour les mineurs ou l'usage DeFi.",
"Value today": "Valeur aujourd'hui",
"Value today (ALPH)": "Valeur aujourd'hui (ALPH)",
"Version": "Version",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "La version {{ newVersion }} est disponible. Cliquez sur \"Mettre à jour\" afin d'éviter tout problème de fonctionnement.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "La version {{ newVersion }} est disponible. Téléchargez et installez la afin d'éviter tout problème de fonctionnement.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/id-ID/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Gunakan jumlah maksimum",
"Use optional passphrase": "Gunakan frasa sandi opsional",
"Useful for miners or DeFi use.": "Berguna untuk penambang atau penggunaan DeFi.",
"Value today": "Nilai hari ini",
"Value today (ALPH)": "Nilai hari ini (ALPH)",
"Version": "Versi",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Versi {{ newVersion }} telah tersedia. Klik \"Perbarui\" untuk menghindari masalah dompet.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Versi {{ newVersion }} telah tersedia. Silakan, unduh dan instal untuk menghindari masalah dompet.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/it-IT/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@
"Use max amount": "Usa l'importo massimo",
"Use optional passphrase": "Usa passphrase opzionale",
"Useful for miners or DeFi use.": "Utile per minatori o uso DeFi.",
"Value today": "Valore oggi",
"Value today (ALPH)": "Valore oggi (ALPH)",
"Version": "Versione",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Versione {{ newVersion }} è disponibile. Clic \"Update\" per evitare qualsiasi problema con il portafoglio.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Versione {{ newVersion }} è disponibile. Per favore, scaricalo e installalo per evitare qualsiasi problema con il portafoglio.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/pt-PT/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Usar o montante máximo",
"Use optional passphrase": "Use optional passphrase",
"Useful for miners or DeFi use.": "Útil para os mineradores ou uso DeFi.",
"Value today": "Value today",
"Value today (ALPH)": "Value today (ALPH)",
"Version": "Versão",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "A versão {{ newVersion }} está disponível. Clique em \"Atualizar\" para evitar qualquer problema com a carteira.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/ru-RU/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Использовать максимальную сумму",
"Use optional passphrase": "Использовать дополнительную парольную фразу",
"Useful for miners or DeFi use.": "Пригодится для майнеров или для использования в DeFi.",
"Value today": "Стоимость на сегодня",
"Value today (ALPH)": "Стоимость на сегодня (ALPH)",
"Version": "Версия",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Версия {{ newVersion }} уже доступна. Нажмите, \"Обновить\", чтобы избежать проблем с кошельком.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Доступна версия {{ newVersion }}. Пожалуйста, скачайте и установите ее, чтобы избежать проблем с кошельком.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/tr-TR/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@
"Use max amount": "Tüm miktarı kullan",
"Use optional passphrase": "Use optional passphrase",
"Useful for miners or DeFi use.": "Madenciler ya da DeFi kullanımı için faydalıdır.",
"Value today": "Value today",
"Value today (ALPH)": "Value today (ALPH)",
"Version": "Sürüm",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "{{ newVersion }} sürümü mevcut. Cüzdan ile ilgili sorun yaşamamak için \"Güncelle\" kısmına tıklayın.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop-wallet/locales/vi-VN/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@
"Use max amount": "Sử dụng tất cả số dư",
"Use optional passphrase": "Sử dụng cụm từ khôi phục tuỳ chỉnh",
"Useful for miners or DeFi use.": "Hữu ích cho thợ đào (miner) hoặc sử dụng DeFi.",
"Value today": "Giá trị hôm nay",
"Value today (ALPH)": "Giá trị hôm nay (ALPH)",
"Version": "Phiên bản",
"Version {{ newVersion }} is available. Click \"Update\" to avoid any issues with the wallet.": "Phiên bản {{ newVersion }} vừa mới được phát hành. Vui lòng nhấn \"Cập nhật\" để khắc phục những lỗi đang hiện có.",
"Version {{ newVersion }} is available. Please, download it and install it to avoid any issues with the wallet.": "Phiên bản {{ newVersion }} vừa mới được phát hành. Vui lòng tải về và cài đặt để khắc phục các lỗi hiện đang có.",
Expand Down
35 changes: 30 additions & 5 deletions apps/desktop-wallet/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
*/

import { AddressHash } from '@alephium/shared'
import { ALPH } from '@alephium/token-list'
import { AnimatePresence } from 'framer-motion'
import { difference } from 'lodash'
import { usePostHog } from 'posthog-js/react'
Expand All @@ -35,14 +36,19 @@ import { useAppDispatch, useAppSelector } from '@/hooks/redux'
import UpdateWalletModal from '@/modals/UpdateWalletModal'
import Router from '@/routes'
import { syncAddressesData, syncAddressesHistoricBalances } from '@/storage/addresses/addressesActions'
import { makeSelectAddressesUnknownTokens, selectAddressIds } from '@/storage/addresses/addressesSelectors'
import {
mvaivre marked this conversation as resolved.
Show resolved Hide resolved
makeSelectAddressesKnownFungibleTokens,
makeSelectAddressesUnknownTokens,
selectAddressIds
} from '@/storage/addresses/addressesSelectors'
import { syncNetworkTokensInfo, syncUnknownTokensInfo } from '@/storage/assets/assetsActions'
import { selectIsTokensMetadataUninitialized } from '@/storage/assets/assetsSelectors'
import {
devModeShortcutDetected,
localStorageDataMigrated,
localStorageDataMigrationFailed
} from '@/storage/global/globalActions'
import { syncTokenPrices, syncTokenPricesHistory } from '@/storage/prices/pricesActions'
import { apiClientInitFailed, apiClientInitSucceeded } from '@/storage/settings/networkActions'
import { systemLanguageMatchFailed, systemLanguageMatchSucceeded } from '@/storage/settings/settingsActions'
import { makeSelectAddressesHashesWithPendingTransactions } from '@/storage/transactions/transactionsSelectors'
Expand Down Expand Up @@ -76,6 +82,13 @@ const App = () => {
const isSyncingAddressData = useAppSelector((s) => s.addresses.syncingAddressData)
const isTokensMetadataUninitialized = useAppSelector(selectIsTokensMetadataUninitialized)
const isLoadingTokensMetadata = useAppSelector((s) => s.assetsInfo.loading)
const isLoadingTokens = useAppSelector((s) => s.addresses.loadingTokens)

const selectAddressesKnownTokens = useMemo(makeSelectAddressesKnownFungibleTokens, [])
const knownTokens = useAppSelector(selectAddressesKnownTokens)
const knownTokenSymbols = knownTokens
.map((token) => token.symbol)
.filter((symbol): symbol is string => symbol !== undefined)
mvaivre marked this conversation as resolved.
Show resolved Hide resolved

const selectAddressesUnknownTokens = useMemo(makeSelectAddressesUnknownTokens, [])
const unknownTokens = useAppSelector(selectAddressesUnknownTokens)
Expand Down Expand Up @@ -189,11 +202,19 @@ const App = () => {

restorePendingTransactions(mempoolTxHashes, storedPendingTxs)
})
dispatch(syncAddressesHistoricBalances())

dispatch(syncTokenPricesHistory({ tokenSymbol: ALPH.symbol.toLowerCase(), currency: settings.fiatCurrency }))
}
} else if (addressesStatus === 'initialized') {
if (!isTokensMetadataUninitialized && !isLoadingTokensMetadata && newUnknownTokens.length > 0) {
dispatch(syncUnknownTokensInfo(newUnknownTokens))
if (!isTokensMetadataUninitialized && !isLoadingTokensMetadata) {
if (newUnknownTokens.length > 0) {
dispatch(syncUnknownTokensInfo(newUnknownTokens))
}

if (!isLoadingTokens) {
dispatch(syncAddressesHistoricBalances())
dispatch(syncTokenPrices({ knownTokenSymbols, currency: settings.fiatCurrency }))
}
}
}
}
Expand All @@ -203,10 +224,14 @@ const App = () => {
assetsInfo.status,
dispatch,
isSyncingAddressData,
isLoadingTokens,
isLoadingTokensMetadata,
isTokensMetadataUninitialized,
network.status,
newUnknownTokens
newUnknownTokens,
knownTokens,
settings.fiatCurrency,
knownTokenSymbols
])

const refreshAddressesData = useCallback(() => {
Expand Down
13 changes: 6 additions & 7 deletions apps/desktop-wallet/src/components/HistoricWorthChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
selectHaveHistoricBalancesLoaded,
selectIsStateUninitialized
} from '@/storage/addresses/addressesSelectors'
import { useGetHistoricalPriceQuery } from '@/storage/assets/priceApiSlice'
import { selectAlphPriceHistory } from '@/storage/prices/pricesSelectors'
import { ChartLength, DataPoint, LatestAmountPerAddress } from '@/types/chart'
import { Currency } from '@/types/settings'
import { CHART_DATE_FORMAT } from '@/utils/constants'
Expand Down Expand Up @@ -67,15 +67,14 @@ const HistoricWorthChart = memo(function HistoricWorthChart({
const addresses = useAppSelector((s) => selectAddresses(s, addressHash ?? (s.addresses.ids as AddressHash[])))
const haveHistoricBalancesLoaded = useAppSelector(selectHaveHistoricBalancesLoaded)
const stateUninitialized = useAppSelector(selectIsStateUninitialized)

const { data: alphPriceHistory } = useGetHistoricalPriceQuery({ currency, days: 365 })
const priceHistory = useAppSelector(selectAlphPriceHistory)

const theme = useTheme()

const [chartData, setChartData] = useState<DataPoint[]>([])

const startingDate = startingDates[length].format('YYYY-MM-DD')
const isDataAvailable = addresses.length !== 0 && haveHistoricBalancesLoaded && !!alphPriceHistory
const isDataAvailable = addresses.length !== 0 && haveHistoricBalancesLoaded && !!priceHistory
const firstItem = chartData.at(0)

useEffect(() => {
Expand All @@ -91,7 +90,7 @@ const HistoricWorthChart = memo(function HistoricWorthChart({
const computeChartDataPoints = (): DataPoint[] => {
const addressesLatestAmount: LatestAmountPerAddress = {}

const dataPoints = alphPriceHistory.map(({ date, price }) => {
const dataPoints = priceHistory.history.map(({ date, value }) => {
let totalAmountPerDate = BigInt(0)

addresses.forEach(({ hash, balanceHistory }) => {
Expand All @@ -108,7 +107,7 @@ const HistoricWorthChart = memo(function HistoricWorthChart({

return {
date,
worth: price * parseFloat(toHumanReadableAmount(totalAmountPerDate))
worth: value * parseFloat(toHumanReadableAmount(totalAmountPerDate))
}
})

Expand All @@ -123,7 +122,7 @@ const HistoricWorthChart = memo(function HistoricWorthChart({
dataPoints = trimInitialZeroDataPoints(dataPoints)

setChartData(getFilteredChartData(dataPoints, startingDate))
}, [addresses, alphPriceHistory, isDataAvailable, latestWorth, startingDate])
}, [addresses, priceHistory, isDataAvailable, latestWorth, startingDate])

if (!isDataAvailable || chartData.length < 2 || !firstItem || latestWorth === undefined) return null

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
selectIsStateUninitialized
} from '@/storage/addresses/addressesSelectors'
import { selectIsTokensMetadataUninitialized } from '@/storage/assets/assetsSelectors'
import { useGetPriceQuery } from '@/storage/assets/priceApiSlice'
import { selectAlphPrice } from '@/storage/prices/pricesSelectors'
import { currencies } from '@/utils/currencies'
import { onEnterOrSpace } from '@/utils/misc'

Expand All @@ -56,7 +56,8 @@ const AddressGridRow = ({ addressHash, className }: AddressGridRowProps) => {
const stateUninitialized = useAppSelector(selectIsStateUninitialized)
const isTokensMetadataUninitialized = useAppSelector(selectIsTokensMetadataUninitialized)
const fiatCurrency = useAppSelector((s) => s.settings.fiatCurrency)
const { data: price, isLoading: isPriceLoading } = useGetPriceQuery(currencies[fiatCurrency].ticker)
const price = useAppSelector(selectAlphPrice)
const isPriceLoading = useAppSelector((s) => s.tokenPrices.loading)

const [isAddressDetailsModalOpen, setIsAddressDetailsModalOpen] = useState(false)

Expand All @@ -66,7 +67,7 @@ const AddressGridRow = ({ addressHash, className }: AddressGridRowProps) => {

if (!address) return null

const fiatBalance = calculateAmountWorth(BigInt(address.balance), price ?? 0)
const fiatBalance = calculateAmountWorth(BigInt(address.balance), price?.price ?? 0)

const hiddenAssetsSymbols = hiddenAssets.filter(({ symbol }) => !!symbol).map(({ symbol }) => symbol)
const nbOfUnknownHiddenAssets = hiddenAssets.filter(({ symbol }) => !symbol).length
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { useAppSelector } from '@/hooks/redux'
import AddressDetailsModal from '@/modals/AddressDetailsModal'
import ModalPortal from '@/modals/ModalPortal'
import { selectAllAddresses, selectIsStateUninitialized } from '@/storage/addresses/addressesSelectors'
import { useGetPriceQuery } from '@/storage/assets/priceApiSlice'
import { selectAlphPrice } from '@/storage/prices/pricesSelectors'
import { Address } from '@/types/addresses'
import { currencies } from '@/utils/currencies'

Expand Down Expand Up @@ -78,7 +78,7 @@ const AddressesContactsList = ({ className, maxHeightInPx }: AddressesContactsLi
const AddressesList = ({ className, isExpanded, onExpand, onAddressClick }: AddressListProps) => {
const addresses = useAppSelector(selectAllAddresses)
const fiatCurrency = useAppSelector((s) => s.settings.fiatCurrency)
const { data: price } = useGetPriceQuery(currencies[fiatCurrency].ticker)
const alphPrice = useAppSelector(selectAlphPrice)
const stateUninitialized = useAppSelector(selectIsStateUninitialized)

const [selectedAddress, setSelectedAddress] = useState<Address>()
Expand All @@ -98,7 +98,7 @@ const AddressesList = ({ className, isExpanded, onExpand, onAddressClick }: Addr
<SkeletonLoader height="15.5px" width="50%" />
) : (
<AmountStyled
value={calculateAmountWorth(BigInt(address.balance), price ?? 0)}
value={calculateAmountWorth(BigInt(address.balance), alphPrice?.price ?? 0)}
isFiat
suffix={currencies[fiatCurrency].symbol}
tabIndex={0}
Expand Down
Loading
Loading