Skip to content

Commit

Permalink
chore(wallet-mobile): wip wire up
Browse files Browse the repository at this point in the history
  • Loading branch information
stackchain committed May 4, 2024
1 parent 19eacc7 commit 2dfda2c
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 49 deletions.
27 changes: 12 additions & 15 deletions apps/wallet-mobile/src/TxHistory/BalanceBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {PairedBalance} from '../components/PairedBalance/PairedBalance'
import {usePrimaryBalance} from '../features/Portfolio/common/hooks/usePrimaryBalance'
import {usePrivacyMode} from '../features/Settings/PrivacyMode/PrivacyMode'
import {useSelectedWallet} from '../features/WalletManager/Context'
import {asQuantity} from '../yoroi-wallets/utils'

export const BalanceBanner = React.forwardRef<ResetErrorRef>((_, ref) => {
const wallet = useSelectedWallet()
Expand All @@ -30,20 +29,14 @@ export const BalanceBanner = React.forwardRef<ResetErrorRef>((_, ref) => {

<TouchableOpacity onPress={() => togglePrivacyMode()} style={styles.button}>
<CenteredRow>
<PrimaryBalance
isPrivacyOff={isPrivacyOff}
primaryBalance={primaryBalance}
privacyPlaceholder={privacyPlaceholder}
/>
<Balance isPrivacyOff={isPrivacyOff} amount={primaryBalance} privacyPlaceholder={privacyPlaceholder} />
</CenteredRow>

<CenteredRow>
<PairedBalance
isPrivacyOff={isPrivacyOff}
amount={{
quantity: asQuantity(primaryBalance.quantity.toString()),
tokenId: primaryBalance.info.id,
}}
amount={primaryBalance}
privacyPlaceholder={privacyPlaceholder}
ref={ref}
/>
</CenteredRow>
Expand All @@ -52,13 +45,17 @@ export const BalanceBanner = React.forwardRef<ResetErrorRef>((_, ref) => {
)
})

type PrimaryBalanceProps = {isPrivacyOff: boolean; primaryBalance: Portfolio.Token.Amount; privacyPlaceholder: string}
const PrimaryBalance = ({isPrivacyOff, primaryBalance, privacyPlaceholder}: PrimaryBalanceProps) => {
type BalanceProps = {isPrivacyOff: boolean; amount: Portfolio.Token.Amount; privacyPlaceholder: string}
const Balance = ({isPrivacyOff, amount, privacyPlaceholder}: BalanceProps) => {
const styles = useStyles()

const balance = isPrivacyOff
? amountFormatter({template: '{{value}} {{symbol}}'})(primaryBalance)
: amountFormatter({template: `${privacyPlaceholder} {{symbol}}`})(primaryBalance)
const balance = React.useMemo(
() =>
!isPrivacyOff
? amountFormatter({template: '{{value}} {{ticker}}'})(amount)
: amountFormatter({template: `${privacyPlaceholder} {{ticker}}`})(amount),
[amount, isPrivacyOff, privacyPlaceholder],
)

return (
<CenteredRow>
Expand Down
26 changes: 11 additions & 15 deletions apps/wallet-mobile/src/components/PairedBalance/PairedBalance.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useTheme} from '@yoroi/theme'
import {Balance} from '@yoroi/types'
import {Portfolio} from '@yoroi/types'
import * as React from 'react'
import {defineMessages, useIntl} from 'react-intl'
import {StyleSheet, Text, TextStyle} from 'react-native'
Expand All @@ -10,13 +10,15 @@ import {useExchangeRate} from '../../yoroi-wallets/hooks'
import {CurrencySymbol} from '../../yoroi-wallets/types'
import {Quantities} from '../../yoroi-wallets/utils'
import {Boundary, ResetError, ResetErrorRef} from '..'
import { splitBigInt } from '@yoroi/common'

type Props = {
amount: Balance.Amount
amount: Portfolio.Token.Amount
privacyPlaceholder: string
isPrivacyOff?: boolean
textStyle?: TextStyle
}
export const PairedBalance = React.forwardRef<ResetErrorRef, Props>(({isPrivacyOff, amount, textStyle}, ref) => {
export const PairedBalance = React.forwardRef<ResetErrorRef, Props>(({isPrivacyOff, amount, textStyle, privacyPlaceholder}, ref) => {
const {currency} = useCurrencyContext()

return (
Expand All @@ -31,13 +33,12 @@ export const PairedBalance = React.forwardRef<ResetErrorRef, Props>(({isPrivacyO
),
}}
>
<Amount isPrivacyOff={isPrivacyOff} amount={amount} textStyle={textStyle} />
<Price isPrivacyOff={isPrivacyOff} amount={amount} privacyPlaceholder={privacyPlaceholder} textStyle={textStyle} />
</Boundary>
)
})

const hiddenPairedTotal = '*.**'
const Amount = ({isPrivacyOff, amount, textStyle}: Props) => {
const Price = ({isPrivacyOff, amount, textStyle, privacyPlaceholder}: Props) => {
const wallet = useSelectedWallet()
const styles = useStyles()
const {currency, config} = useCurrencyContext()
Expand All @@ -46,20 +47,15 @@ const Amount = ({isPrivacyOff, amount, textStyle}: Props) => {
// hide pairing when set to the primary token
if (currency === 'ADA') return null

// hide pairing when the amount is not primary
if (wallet.primaryTokenInfo.id !== amount.tokenId) return null

if (rate == null)
return (
<Text style={[styles.pairedBalanceText, textStyle]} testID="pairedTotalText">
<Text style={[styles.pairedBalanceText, textStyle]}>
... {currency}
</Text>
)

const primaryExchangeQuantity = Quantities.quotient(
amount.quantity,
`${10 ** wallet.primaryToken.metadata.numberOfDecimals}`,
)
const price = splitBigInt()

const secondaryExchangeQuantity = Quantities.decimalPlaces(
Quantities.product([primaryExchangeQuantity, `${rate}`]),
config.decimals,
Expand All @@ -78,7 +74,7 @@ const BalanceError = ({textStyle}: {textStyle?: TextStyle}) => {
const {currency} = useCurrencyContext()

return (
<Text style={[styles.pairedBalanceText, textStyle]} testID="pairedTotalText">
<Text style={[styles.pairedBalanceText, textStyle]}>
{strings.pairedBalanceError(currency)}
</Text>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ export const usePortfolioTokenManager = ({network}: {network: Chain.Network}) =>
}

export const buildPortfolioTokenManager = ({network}: {network: Chain.Network}) => {
const networkStorageMounted = mountMMKVStorage<Portfolio.Token.Id>({path: '/', id: `${network}.token-manager`})
const tokenDiscoveryStorageMounted = networkStorageMounted.join('token-discovery/')
const tokenInfoStorageMounted = networkStorageMounted.join('token-info/')
const storage = mountMMKVStorage<Portfolio.Token.Id>({path: '/', id: `${network}.token-manager`})
const tokenDiscoveryStorageMounted = storage.join('token-discovery/')
const tokenInfoStorageMounted = storage.join('token-info/')

const tokenStorage = portfolioTokenStorageMaker({
tokenDiscoveryStorage: observableStorageMaker(tokenDiscoveryStorageMounted),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
"defaultMessage": "!!!Error obtaining {currency} pairing",
"file": "src/components/PairedBalance/PairedBalance.tsx",
"start": {
"line": 88,
"line": 84,
"column": 22,
"index": 2781
"index": 2633
},
"end": {
"line": 91,
"line": 87,
"column": 3,
"index": 2913
"index": 2765
}
}
]
12 changes: 6 additions & 6 deletions packages/common/src/storage/adapters/mmkv-storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import {parseSafe} from '../../utils/parsers'
import {mountMMKVMultiStorage, mountMMKVStorage} from './mmkv-storage'
import {MMKV} from 'react-native-mmkv'

const mmkv = new MMKV({id: 'default.mmkv'})
const mmkv = new MMKV({id: 'test.mmkv'})
const rootStorage = mountMMKVStorage(
{path: '/', id: 'default.mmkv'},
{path: '/', id: 'test.mmkv'},
{instance: mmkv},
)

Expand Down Expand Up @@ -129,12 +129,12 @@ describe('prefixed storage', () => {
rootStorage.setItem('item', item, (data: unknown) => {
expect(data).toBe(item)
return storedItem
}) // overrides JSON.stringify
})

const parsedResult = rootStorage.getItem('item', (data: unknown) => {
expect(data).toBe(storedItem)
return item
}) // overrides JSON.parse
})

expect(parsedResult).toBe(item)
})
Expand All @@ -152,15 +152,15 @@ describe('prefixed storage', () => {
rootStorage.multiSet(tuples, (data: unknown) => {
expect([item1, item2]).toContain(data)
return `${data}-modified`
}) // overrides JSON.stringify
})

const parsedResult = rootStorage.multiGet(
['item1', 'item2'],
(data: string | null) => {
expect([storedItem1, storedItem2]).toContain(data)
return data?.slice(0, 5)
},
) // overrides JSON.parse
)

expect(parsedResult).toEqual(tuples)
})
Expand Down
7 changes: 1 addition & 6 deletions packages/common/src/storage/adapters/mmkv-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import {parseSafe} from '../../utils/parsers'
import {isFolderKey} from '../helpers/is-folder-key'
import {isFileKey} from '../helpers/is-file-key'

// -------
// FACTORY
export const mountMMKVStorage = <Key extends string = string>(
{
path,
Expand All @@ -17,10 +15,7 @@ export const mountMMKVStorage = <Key extends string = string>(
},
{instance}: {instance?: MMKV} = {},
): App.Storage<false, Key> => {
// mmkv uses id as file and the path is irrelevant if sharing content amongst app (iOS)
// therefore the client needs to know all the ids to delete all data
// which means that it works differently than AsyncStorage
// think of the id as the volume
// think of the id as the filename and the path as filter
const storage = instance ?? new MMKV({id})

const withPath = (key: string) =>
Expand Down
18 changes: 18 additions & 0 deletions packages/portfolio/src/helpers/amount-breakdown.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import BigNumber from 'bignumber.js'
import {tokenBalanceMocks} from '../adapters/token-balance.mocks'
import {amountBreakdown} from './amount-breakdown'

describe('amountBreakdown', () => {
it('should correctly split the quantity based on decimals', () => {
const result = amountBreakdown(tokenBalanceMocks.primaryETH)

expect(result).toEqual({
bi: 1000000n,
bn: new BigNumber('1e-12'),
decimalPlaces: 18,
fraction: '000000000001000000',
integer: '0',
str: '0.000000000001000000',
})
})
})
6 changes: 6 additions & 0 deletions packages/portfolio/src/helpers/amount-breakdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {splitBigInt} from '@yoroi/common'
import {Portfolio} from '@yoroi/types'

export function amountBreakdown({quantity, info}: Portfolio.Token.Amount) {
return splitBigInt(quantity, info.decimals)
}
1 change: 1 addition & 0 deletions packages/portfolio/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './helpers/amount-formatter'
export * from './helpers/amount-breakdown'
export * from './helpers/create-primary-token-info'
export * from './helpers/sorting'

Expand Down

0 comments on commit 2dfda2c

Please sign in to comment.