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

Jon/fix/coin-rank-default-fiat #4154

Merged
merged 3 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 19 additions & 9 deletions src/components/charts/SwipeChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import { getSymbolFromCurrency } from '../../constants/WalletAndCurrencyConstant
import { formatFiatString } from '../../hooks/useFiatText'
import { useHandler } from '../../hooks/useHandler'
import { formatDate } from '../../locales/intl'
import { lstrings } from '../../locales/strings'
import { getDefaultFiat } from '../../selectors/SettingsSelectors'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pass fiat as param from router

import { useSelector } from '../../types/reactRedux'
import { MinimalButton } from '../buttons/MinimalButton'
import { FillLoader } from '../progress-indicators/FillLoader'
import { showWarning } from '../services/AirshipInstance'
Expand Down Expand Up @@ -43,7 +46,7 @@ interface Props {
assetId: string // The asset's 'id' as defined by CoinGecko
}

const DATASET_URL_3S = 'https://api.coingecko.com/api/v3/coins/%1$s/market_chart/range?vs_currency=USD&from=%2$s&to=%3$s'
const DATASET_URL_4S = 'https://api.coingecko.com/api/v3/coins/%1$s/market_chart/range?vs_currency=%2$s&from=%3$s&to=%4$s'
const UNIX_SECONDS_HOUR_OFFSET = 60 * 60
const UNIX_SECONDS_DAY_OFFSET = 24 * UNIX_SECONDS_HOUR_OFFSET
const UNIX_SECONDS_WEEK_OFFSET = 7 * UNIX_SECONDS_DAY_OFFSET
Expand Down Expand Up @@ -119,6 +122,8 @@ const SwipeChartComponent = (params: Props) => {

// #region Chart setup

const defaultFiat = useSelector(state => getDefaultFiat(state))

const [chartData, setChartData] = React.useState<ChartDataPoint[]>([])
const [cachedTimespanChartData, setCachedChartData] = React.useState<Map<Timespan, ChartDataPoint[] | undefined>>(
new Map<Timespan, ChartDataPoint[] | undefined>([
Expand All @@ -137,7 +142,7 @@ const SwipeChartComponent = (params: Props) => {
const chartWidth = React.useRef(0)
const chartHeight = React.useRef(0)

const fiatSymbol = React.useMemo(() => getSymbolFromCurrency('iso:USD'), [])
const fiatSymbol = React.useMemo(() => getSymbolFromCurrency(defaultFiat), [defaultFiat])

// Min/Max Price Calcs
const prices = React.useMemo(() => chartData.map(dataPoint => dataPoint.y), [chartData])
Expand Down Expand Up @@ -183,12 +188,17 @@ const SwipeChartComponent = (params: Props) => {
// Construct the dataset query
const unixNow = Math.trunc(new Date().getTime() / 1000)
const fromParam = unixNow - queryFromTimeOffset
const fetchUrl = sprintf(DATASET_URL_3S, assetId, fromParam, unixNow)
const fetchUrl = sprintf(DATASET_URL_4S, assetId, defaultFiat, fromParam, unixNow)
fetch(fetchUrl)
.then(async res => await res.json())
.then((data: any) => {
const marketChartRange = asCoinGeckoMarketChartRange(data)
const rawChartData = marketChartRange.prices.map(rawDataPoint => ({ x: new Date(rawDataPoint[0]), y: rawDataPoint[1] }))
const rawChartData = marketChartRange.prices.map(rawDataPoint => {
return {
x: new Date(rawDataPoint[0]),
y: rawDataPoint[1]
}
})
const reducedChartData = reduceChartData(rawChartData, selectedTimespan)

setChartData(reducedChartData)
Expand Down Expand Up @@ -493,11 +503,11 @@ const SwipeChartComponent = (params: Props) => {
<View style={styles.container}>
{/* Timespan control bar */}
<View style={styles.controlBar}>
{renderTimespanButton('H', 'hour', handleSetTimespanH)}
{renderTimespanButton('D', 'day', handleSetTimespanD)}
{renderTimespanButton('W', 'week', handleSetTimespanW)}
{renderTimespanButton('M', 'month', handleSetTimespanM)}
{renderTimespanButton('Y', 'year', handleSetTimespanY)}
{renderTimespanButton(lstrings.coin_rank_hour, 'hour', handleSetTimespanH)}
{renderTimespanButton(lstrings.coin_rank_day, 'day', handleSetTimespanD)}
{renderTimespanButton(lstrings.coin_rank_week, 'week', handleSetTimespanW)}
{renderTimespanButton(lstrings.coin_rank_month, 'month', handleSetTimespanM)}
{renderTimespanButton(lstrings.coin_rank_year, 'year', handleSetTimespanY)}
</View>

{/* Chart */}
Expand Down
13 changes: 9 additions & 4 deletions src/components/data/row/CoinRankRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ import { TouchableOpacity, View } from 'react-native'
import FastImage from 'react-native-fast-image'
import { cacheStyles } from 'react-native-patina'

import { getSymbolFromCurrency } from '../../../constants/WalletAndCurrencyConstants'
import { formatFiatString } from '../../../hooks/useFiatText'
import { useHandler } from '../../../hooks/useHandler'
import { toPercentString } from '../../../locales/intl'
import { getDefaultFiat } from '../../../selectors/SettingsSelectors'
import { AssetSubText, CoinRanking, CoinRankingData, PercentChangeTimeFrame } from '../../../types/coinrankTypes'
import { useState } from '../../../types/reactHooks'
import { useSelector } from '../../../types/reactRedux'
import { NavigationProp } from '../../../types/routerTypes'
import { triggerHaptic } from '../../../util/haptic'
import { debugLog, LOG_COINRANK } from '../../../util/logger'
Expand All @@ -31,6 +35,9 @@ const CoinRankRowComponent = (props: Props) => {
const { navigation, index, percentChangeTimeFrame, assetSubText, coinRanking } = props
const { coinRankingDatas } = coinRanking

const defaultFiat = useSelector(state => getDefaultFiat(state))
const fiatSymbol = React.useMemo(() => getSymbolFromCurrency(defaultFiat), [defaultFiat])

const mounted = React.useRef<boolean>(true)
const timeoutHandler = React.useRef<Timeout | undefined>()

Expand Down Expand Up @@ -90,8 +97,6 @@ const CoinRankRowComponent = (props: Props) => {
const { currencyCode, price, marketCap, volume24h, percentChange, rank } = coinRow
debugLog(LOG_COINRANK, `CoinRankRow index=${index} rank=${rank} currencyCode=${currencyCode}`)

const fiatSymbol = '$'

let numDecimals
let assetSubTextValue

Expand Down Expand Up @@ -125,15 +130,15 @@ const CoinRankRowComponent = (props: Props) => {
// Calculate percent change string
const percentChangeRaw = percentChange[percentChangeTimeFrame]
numDecimals = getNumDecimals(percentChangeRaw, 2)
const percentChangeString = round(percentChangeRaw.toString(), -numDecimals)
const percentChangeString = toPercentString(percentChangeRaw / 100, { noGrouping: true })
const negative = lt(percentChangeString, '0')

// Calculate price string
numDecimals = getNumDecimals(price)
const priceStyle = negative ? styles.negativeText : styles.positiveText
const plusMinus = negative ? '' : '+'
const priceString = `${fiatSymbol}${formatFiatString({ fiatAmount: price.toString() })}`
const percentString = `${plusMinus}${percentChangeString}%`
const percentString = `${plusMinus}${percentChangeString}`

return (
<TouchableOpacity style={styles.container} onPress={handlePress}>
Expand Down
11 changes: 9 additions & 2 deletions src/components/scenes/CoinRankingDetailsScene.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import * as React from 'react'
import { ScrollView, View } from 'react-native'
import FastImage from 'react-native-fast-image'

import { USD_FIAT } from '../../constants/WalletAndCurrencyConstants'
import { formatFiatString } from '../../hooks/useFiatText'
import { toLocaleDate, toPercentString } from '../../locales/intl'
import { lstrings } from '../../locales/strings'
import { getDefaultFiat } from '../../selectors/SettingsSelectors'
import { CoinRankingData, CoinRankingDataPercentChange } from '../../types/coinrankTypes'
import { useSelector } from '../../types/reactRedux'
import { RouteProp } from '../../types/routerTypes'
import { formatLargeNumberString as formatLargeNumber } from '../../util/utils'
import { SwipeChart } from '../charts/SwipeChart'
Expand All @@ -16,6 +17,10 @@ import { EdgeText } from '../themed/EdgeText'

type CoinRankingDataValueType = string | number | CoinRankingDataPercentChange | undefined

export interface CoinRankingDetailsParams {
coinRankingData: CoinRankingData
}

interface Props {
route: RouteProp<'coinRankingDetails'>
}
Expand Down Expand Up @@ -75,6 +80,8 @@ const CoinRankingDetailsSceneComponent = (props: Props) => {
const { currencyCode, currencyName } = coinRankingData
const currencyCodeUppercase = currencyCode.toUpperCase()

const defaultFiat = useSelector(state => getDefaultFiat(state))

const imageUrlObject = React.useMemo(
() => ({
uri: coinRankingData.imageUrl ?? ''
Expand Down Expand Up @@ -107,7 +114,7 @@ const CoinRankingDetailsSceneComponent = (props: Props) => {
case 'priceChange24h':
case 'high24h':
case 'low24h':
return `${formatFiatString({ fiatAmount: baseString })} ${USD_FIAT.replace('iso:', '')}`
return `${formatFiatString({ fiatAmount: baseString })} ${defaultFiat}`
case 'rank':
return `#${baseString}`
case 'marketCapChange24h':
Expand Down
8 changes: 6 additions & 2 deletions src/components/scenes/CoinRankingScene.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import { TouchableOpacity, View } from 'react-native'
import { useAsyncEffect } from '../../hooks/useAsyncEffect'
import { useHandler } from '../../hooks/useHandler'
import { lstrings } from '../../locales/strings'
import { getDefaultFiat } from '../../selectors/SettingsSelectors'
import { asCoinranking, AssetSubText, CoinRanking, PercentChangeTimeFrame } from '../../types/coinrankTypes'
import { useState } from '../../types/reactHooks'
import { useSelector } from '../../types/reactRedux'
import { NavigationProp } from '../../types/routerTypes'
import { FlatListItem } from '../../types/types'
import { debugLog, enableDebugLogType, LOG_COINRANK } from '../../util/logger'
Expand Down Expand Up @@ -50,6 +52,9 @@ const CoinRankingComponent = (props: Props) => {
const theme = useTheme()
const styles = getStyles(theme)
const { navigation } = props

const defaultIsoFiat = useSelector(state => `iso:${getDefaultFiat(state)}`)

const mounted = React.useRef<boolean>(true)
const textInput = React.useRef<OutlinedTextInputRef>(null)
const timeoutHandler = React.useRef<Timeout | undefined>()
Expand All @@ -60,7 +65,6 @@ const CoinRankingComponent = (props: Props) => {
const [searching, setSearching] = useState<boolean>(false)
const [percentChangeTimeFrame, setPercentChangeTimeFrame] = useState<PercentChangeTimeFrame>('hours24')
const [assetSubText, setPriceSubText] = useState<AssetSubText>('marketCap')
const [fiatCode] = useState<string>('iso:USD')
const extraData = React.useMemo(() => ({ assetSubText, percentChangeTimeFrame }), [assetSubText, percentChangeTimeFrame])

const { coinRankingDatas } = coinRanking
Expand Down Expand Up @@ -139,7 +143,7 @@ const CoinRankingComponent = (props: Props) => {
let start = 1
debugLog(LOG_COINRANK, `queryLoop dataSize=${dataSize} requestDataSize=${requestDataSize}`)
while (start < requestDataSize) {
const url = `v2/coinrank?fiatCode=${fiatCode}&start=${start}&length=${QUERY_PAGE_SIZE}`
const url = `v2/coinrank?fiatCode=${defaultIsoFiat}&start=${start}&length=${QUERY_PAGE_SIZE}`
const response = await fetchRates(url)
if (!response.ok) {
const text = await response.text()
Expand Down
5 changes: 5 additions & 0 deletions src/locales/en_US.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1277,6 +1277,11 @@ const strings = {
coin_rank_title_all_time_low: 'All Time Low',
coin_rank_market_cap_abbreviation: 'MCap',
coin_rank_volume_24hr_abbreviation: 'Vol 24h',
coin_rank_hour: '1H',
coin_rank_day: '24H',
coin_rank_week: '7D',
coin_rank_month: '30D',
coin_rank_year: '1Y',

// #endregion CoinRanking

Expand Down
5 changes: 5 additions & 0 deletions src/locales/strings/enUS.json
Original file line number Diff line number Diff line change
Expand Up @@ -1114,6 +1114,11 @@
"coin_rank_title_all_time_low": "All Time Low",
"coin_rank_market_cap_abbreviation": "MCap",
"coin_rank_volume_24hr_abbreviation": "Vol 24h",
"coin_rank_hour": "1H",
"coin_rank_day": "24H",
"coin_rank_week": "7D",
"coin_rank_month": "30D",
"coin_rank_year": "1Y",
"form_field_title_account_owner": "Account Owner",
"form_field_title_address_city": "City",
"form_field_title_address_country": "Country",
Expand Down
6 changes: 2 additions & 4 deletions src/types/routerTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ParamListBase, StackActionHelpers } from '@react-navigation/native'
import { EdgeCurrencyInfo, EdgeCurrencyWallet, EdgeSpendInfo, EdgeTransaction, JsonObject, OtpError } from 'edge-core-js'
import { InitialRouteName } from 'edge-login-ui-rn'

import { CoinRankingDetailsParams } from '../components/scenes/CoinRankingDetailsScene'
import { ConfirmSceneParams } from '../components/scenes/ConfirmScene'
import { FioCreateHandleProps } from '../components/scenes/Fio/FioCreateHandleScene'
import { PluginViewParams } from '../components/scenes/GuiPluginViewScene'
Expand All @@ -16,7 +17,6 @@ import { BorrowEngine, BorrowPlugin } from '../plugins/borrow-plugins/types'
import { FiatPluginAddressFormParams, FiatPluginSepaFormParams, FiatPluginSepaTransferParams } from '../plugins/gui/fiatPluginTypes'
import { FiatPluginEnterAmountParams } from '../plugins/gui/scenes/FiatPluginEnterAmountScene'
import { ChangeQuoteRequest, StakePlugin, StakePolicy, StakePosition } from '../plugins/stake-plugins/types'
import { CoinRankingData } from './coinrankTypes'
import {
CreateWalletType,
EdgeTokenId,
Expand Down Expand Up @@ -74,9 +74,7 @@ interface RouteParamList {
changePassword: {}
changePin: {}
coinRanking: {}
coinRankingDetails: {
coinRankingData: CoinRankingData
}
coinRankingDetails: CoinRankingDetailsParams
confirmScene: ConfirmSceneParams
createWalletAccountSelect: {
accountName: string
Expand Down