Skip to content

Commit

Permalink
chore: dissolve currency file (#5057)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxwellmattryan committed Oct 31, 2022
1 parent 66c596d commit a6edaef
Show file tree
Hide file tree
Showing 47 changed files with 408 additions and 468 deletions.
2 changes: 1 addition & 1 deletion docs/guides/coding-conventions/comments.md
Expand Up @@ -181,7 +181,7 @@ When writing functions that return neither `void` nor `Promise<void>` nor `boole
/**
* Returns the converted amount in fiat from IOTAs.
*/
export function convertToFiat(amount: number, usdPrice: number, conversionRate: number): number {
export function miotaToFiat(amount: number, usdPrice: number, conversionRate: number): number {
...
}
```
Expand Down
@@ -1,6 +1,6 @@
<script lang="typescript">
import { Dropdown, Text } from 'shared/components'
import { exchangeRates } from 'shared/lib/currency'
import { exchangeRates } from '@core/utils'
import { localize } from '@core/i18n'
import { activeProfile, updateActiveProfileSettings } from '@core/profile'
import type { IDropdownChoice } from '@core/utils'
Expand Down
3 changes: 1 addition & 2 deletions packages/shared/components/inputs/AssetAmountInput.svelte
Expand Up @@ -2,8 +2,7 @@
import Big from 'big.js'
import { Text, AssetDropdown, InputContainer, AmountInput, TooltipIcon } from 'shared/components'
import UnitInput from './UnitInput.svelte'
import { parseCurrency } from '@lib/currency'
import { localize } from '@core/i18n'
import { localize, parseCurrency } from '@core/i18n'
import {
formatTokenAmountBestMatch,
convertToRawAmount,
Expand Down
5 changes: 2 additions & 3 deletions packages/shared/components/inputs/Input.svelte
@@ -1,7 +1,7 @@
<script lang="typescript">
import { onMount, createEventDispatcher, tick } from 'svelte'
import { Text, InputContainer, TextPropTypes, TextType } from 'shared/components'
import { formatNumber, getAllDecimalSeparators, getDecimalSeparator, parseCurrency } from '@lib/currency'
import { DECIMAL_SEPARATORS, formatNumber, getDecimalSeparator, parseCurrency } from '@core/i18n'
import { localize } from '@core/i18n'
export let value: string = ''
Expand Down Expand Up @@ -31,7 +31,6 @@
export let hasFocus = false
const dispatch = createEventDispatcher()
const allDecimalSeparators = getAllDecimalSeparators()
const decimalSeparator = getDecimalSeparator()
let capsLockOn = false
Expand Down Expand Up @@ -101,7 +100,7 @@
}
} else if (integer) {
// Dicard anything with a decimal separator
if (allDecimalSeparators.some((sep) => pasteVal?.indexOf(sep) >= 0)) {
if (DECIMAL_SEPARATORS.some((sep) => pasteVal?.indexOf(sep) >= 0)) {
event.preventDefault()
} else {
const val = Number.parseInt(pasteVal, 10)
Expand Down
5 changes: 2 additions & 3 deletions packages/shared/components/popups/ActivityDetailsPopup.svelte
Expand Up @@ -14,8 +14,7 @@
selectedAccountActivities,
} from '@core/wallet'
import { activeProfile, checkActiveProfileAuth } from '@core/profile'
import { currencies, exchangeRates } from '@lib/currency'
import { CurrencyTypes } from 'shared/lib/typings/currency'
import { currencies, Currency, exchangeRates } from '@core/utils'
import { setClipboard } from '@core/utils'
import { truncateString } from '@core/utils'
import { closePopup, openPopup } from '@auxiliary/popup'
Expand Down Expand Up @@ -48,7 +47,7 @@
transactionTime: activity.time,
inclusionState: activity.inclusionState,
formattedFiatValue: activity.getFiatAmount(
$currencies[CurrencyTypes.USD],
$currencies[Currency.USD],
$exchangeRates[$activeProfile?.settings?.currency]
),
}
Expand Down
Expand Up @@ -33,9 +33,9 @@
newTransactionDetails,
updateNewTransactionDetails,
} from '@core/wallet'
import { convertToFiat, currencies, exchangeRates, formatCurrency } from '@lib/currency'
import { formatCurrency } from '@core/i18n'
import { currencies, Currency, exchangeRates, miotaToFiat } from '@core/utils'
import { closePopup, openPopup } from '@auxiliary/popup'
import { CurrencyTypes } from '@lib/typings/currency'
import { BaseError } from '@core/error'
import { ledgerPreparedOutput } from '@core/ledger'
Expand Down Expand Up @@ -69,11 +69,7 @@
$: formattedFiatValue =
formatCurrency(
convertToFiat(
Big(rawAmount),
$currencies[CurrencyTypes.USD],
$exchangeRates[$activeProfile?.settings?.currency]
)
miotaToFiat(Big(rawAmount), $currencies[Currency.USD], $exchangeRates[$activeProfile?.settings?.currency])
) || ''
$: transactionDetails = {
Expand Down
@@ -0,0 +1 @@
export const DECIMAL_SEPARATORS = ['.', ',']
@@ -0,0 +1,9 @@
import { LocaleOptions } from '../types'

export const DEFAULT_LOCALE_OPTIONS: LocaleOptions = {
fallbackLocale: 'en',
initialLocale: null,
loadingDelay: 200,
formats: {},
warnOnMissingMessages: true,
}
4 changes: 3 additions & 1 deletion packages/shared/lib/core/i18n/constants/index.ts
@@ -1 +1,3 @@
export * from './locale'
export * from './decimal-separators.constant'
export * from './default-locale-options.constant'
export * from './supported-locales.constant'
@@ -1,20 +1,3 @@
import { LocaleOptions } from '../types'

/**
* The default locale options, useful for when a specific
* translation is not supported.
*/
export const DEFAULT_LOCALE_OPTIONS: LocaleOptions = {
fallbackLocale: 'en',
initialLocale: null,
loadingDelay: 200,
formats: {},
warnOnMissingMessages: true,
}

/**
* The available locales supported by the app.
*/
export const SUPPORTED_LOCALES = {
en: 'English',
af: 'Afrikaans',
Expand Down
1 change: 1 addition & 0 deletions packages/shared/lib/core/i18n/index.ts
Expand Up @@ -2,6 +2,7 @@
export * from './constants'
export * from './stores'
export * from './types'
export * from './utils'

// FILES
export * from './i18n'
25 changes: 25 additions & 0 deletions packages/shared/lib/core/i18n/utils/ensureZeroes.ts
@@ -0,0 +1,25 @@
import { getDecimalSeparator } from './getDecimalSeparator'

export function ensureZeroes(val: string, maxZeros: number): string {
const decimalSeparator = getDecimalSeparator()

const parts = val.split(decimalSeparator)

if (parts.length === 1) {
parts[1] = ''
if (maxZeros > 0) {
parts[1].padEnd(maxZeros, '0')
}
}

// If there are more then decimal places and it is just 0s remove them
if (parts[1].length > maxZeros) {
parts[1] = `${parts[1].slice(0, maxZeros)}${parts[1].slice(maxZeros).replace(/0+$/, '')}`
}

if (parts[1].length > 0) {
return `${parts[0]}${decimalSeparator}${parts[1]}`
} else {
return parts[0]
}
}
46 changes: 46 additions & 0 deletions packages/shared/lib/core/i18n/utils/formatCurrency.ts
@@ -0,0 +1,46 @@
import { get } from 'svelte/store'

import { appSettings } from '@core/app'
import { activeProfile } from '@core/profile'

export function formatCurrency(
value: number,
currency: string | undefined = undefined,
minDecimals: number | undefined = undefined,
maxDecimals: number | undefined = undefined,
grouped: boolean = false
): string {
if (Number.isNaN(value)) {
return ''
}

const appLanguage = get(appSettings).language

if (!currency) {
currency = get(activeProfile)?.settings?.currency
}

const parts = Intl.NumberFormat(appLanguage, {
style: 'currency',
currency: currency ?? 'USD',
currencyDisplay: 'symbol',
minimumFractionDigits: minDecimals ?? 2,
maximumFractionDigits: maxDecimals,
useGrouping: grouped,
}).formatToParts(value)

// Default symbol usage does not always include a literal beside
// the
const curIndex = parts.findIndex((p) => p.type === 'currency')
if (curIndex >= 0) {
if (curIndex === 0) {
if (parts[curIndex + 1].type !== 'literal') {
parts.splice(curIndex + 1, 0, { type: 'literal', value: ' ' })
}
} else if (parts[curIndex - 1].type !== 'literal') {
parts.splice(curIndex, 0, { type: 'literal', value: ' ' })
}
}

return parts.map((p) => p.value).join('')
}
23 changes: 23 additions & 0 deletions packages/shared/lib/core/i18n/utils/formatCurrencyValue.ts
@@ -0,0 +1,23 @@
import { Currency, formatIotaUnitBestMatch } from '@core/utils'

import { replaceCurrencyDecimal } from './replaceCurrencyDecimal'

export function formatCurrencyValue(
data: number | string,
currency: string,
fiatFixed: number = 2,
btcFixed: number = 7,
ethFixed: number = 6
): string {
const parsedData: number = parseFloat(data.toString())
switch (currency.toLowerCase()) {
case Currency.IOTA:
return formatIotaUnitBestMatch(parsedData)
case Currency.BTC:
return replaceCurrencyDecimal(parsedData.toFixed(btcFixed), 'USD')
case Currency.ETH:
return replaceCurrencyDecimal(parsedData.toFixed(ethFixed), 'USD')
default:
return replaceCurrencyDecimal(parsedData.toFixed(fiatFixed), currency)
}
}
34 changes: 34 additions & 0 deletions packages/shared/lib/core/i18n/utils/formatNumber.ts
@@ -0,0 +1,34 @@
import { get } from 'svelte/store'

import { appSettings } from '@core/app'

import { ensureZeroes } from './ensureZeroes'

export function formatNumber(
value: number,
minDecimals: number | undefined = undefined,
maxDecimals: number | undefined = undefined,
maxZeros: number = 2,
grouped: boolean = false
): string {
// The decimals are truncated anyway if the value is larger than what JS can represent safely.
if (value > Number.MAX_SAFE_INTEGER) {
return String(value)
}

// The maximum decimals are equal to the max decimals of Ethereum.
// Larger values throw an error when trying to format.
if (maxDecimals > 18) {
return String(value)
}

const appLanguage = get(appSettings).language

const formatted = Intl.NumberFormat(appLanguage, {
minimumFractionDigits: minDecimals ?? 2,
maximumFractionDigits: maxDecimals,
useGrouping: grouped,
}).format(value)

return ensureZeroes(formatted, maxZeros)
}
14 changes: 14 additions & 0 deletions packages/shared/lib/core/i18n/utils/getCurrencyPosition.ts
@@ -0,0 +1,14 @@
import { get } from 'svelte/store'

import { appSettings } from '@core/app'

export function getCurrencyPosition(): 'left' | 'right' {
const appLanguage = get(appSettings).language

const format = Intl.NumberFormat(appLanguage, {
style: 'currency',
currency: 'USD',
}).formatToParts(1.1)

return format.findIndex((p) => p.type === 'currency') === 0 ? 'left' : 'right'
}
21 changes: 21 additions & 0 deletions packages/shared/lib/core/i18n/utils/getDecimalSeparator.ts
@@ -0,0 +1,21 @@
import { get } from 'svelte/store'

import { appSettings } from '@core/app'
import { activeProfile } from '@core/profile'

export function getDecimalSeparator(currency: string | undefined = undefined): string {
const appLanguage = get(appSettings).language

if (!currency) {
currency = get(activeProfile)?.settings?.currency
}

return (
Intl.NumberFormat(appLanguage, {
style: 'currency',
currency: currency ?? 'USD',
})
.formatToParts(1.1)
.find((part) => part.type === 'decimal')?.value ?? '.'
)
}
21 changes: 21 additions & 0 deletions packages/shared/lib/core/i18n/utils/getGroupSeparator.ts
@@ -0,0 +1,21 @@
import { get } from 'svelte/store'

import { appSettings } from '@core/app'
import { activeProfile } from '@core/profile'

export function getGroupSeparator(currency: string | undefined = undefined): string {
const appLanguage = get(appSettings).language

if (!currency) {
currency = get(activeProfile)?.settings?.currency
}

return (
Intl.NumberFormat(appLanguage, {
style: 'currency',
currency: currency ?? 'USD',
})
.formatToParts(1111111)
.find((part) => part.type === 'group')?.value ?? ','
)
}
9 changes: 9 additions & 0 deletions packages/shared/lib/core/i18n/utils/index.ts
@@ -0,0 +1,9 @@
export * from './ensureZeroes'
export * from './formatCurrency'
export * from './formatCurrencyValue'
export * from './formatNumber'
export * from './getCurrencyPosition'
export * from './getDecimalSeparator'
export * from './getGroupSeparator'
export * from './parseCurrency'
export * from './replaceCurrencyDecimal'
8 changes: 8 additions & 0 deletions packages/shared/lib/core/i18n/utils/parseCurrency.ts
@@ -0,0 +1,8 @@
import { getDecimalSeparator } from './getDecimalSeparator'
import { getGroupSeparator } from './getGroupSeparator'

export function parseCurrency(valueString: string, currency: string | undefined = undefined): number {
// Need to escape the character in the regex in case it is . otherwise it will replace all characters
const v = valueString?.replace(new RegExp(`\\${getGroupSeparator()}`, 'g'), '')
return Number.parseFloat(v?.replace(getDecimalSeparator(currency), '.'))
}
5 changes: 5 additions & 0 deletions packages/shared/lib/core/i18n/utils/replaceCurrencyDecimal.ts
@@ -0,0 +1,5 @@
import { getDecimalSeparator } from './getDecimalSeparator'

export function replaceCurrencyDecimal(value: string, currency: string | undefined = undefined): string {
return value.replace('.', getDecimalSeparator(currency))
}
@@ -1,5 +1,6 @@
import { NetworkProtocol, NetworkType } from '@core/network'
import { AvailableExchangeRates } from '@lib/typings/currency'
import { ExchangeRate } from '@core/utils'

import { ProfileType } from '../enums'
import { IPersistedProfile } from '../interfaces'
import { PROFILE_VERSION } from './profile-version.constant'
Expand All @@ -13,7 +14,7 @@ export const DEFAULT_ACTIVE_PROFILE_VALUE: IPersistedProfile = {
networkType: NetworkType?.Mainnet,
lastStrongholdBackupTime: new Date(),
settings: {
currency: AvailableExchangeRates.USD,
currency: ExchangeRate.USD,
lockScreenTimeoutInMinutes: 5,
hideNetworkStatistics: true,
},
Expand Down
@@ -1,7 +1,7 @@
import { AvailableExchangeRates } from '@lib/typings/currency'
import { ExchangeRate } from '@core/utils'

export interface IProfileSettings {
currency: AvailableExchangeRates
currency: ExchangeRate
lockScreenTimeoutInMinutes: number
hideNetworkStatistics: boolean
}

0 comments on commit a6edaef

Please sign in to comment.