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

wallet address context #411

Merged
merged 1 commit into from
Aug 4, 2021
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions app/components/OceanInterface/OceanInterface.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ jest.mock('../../contexts/WalletContext', () => ({
})
}))

jest.mock("../../contexts/WalletAddressContext", () => ({
useWalletAddressContext: () => {
return {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d'
}
}
}));

describe('oceanInterface', () => {
it('should match snapshot with error', async () => {
const initialState: Partial<RootState> = {
Expand All @@ -24,7 +32,6 @@ describe('oceanInterface', () => {
err: new Error('An unknown error has occurred')
},
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand Down Expand Up @@ -56,7 +63,6 @@ describe('oceanInterface', () => {
}]
},
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand Down
3 changes: 2 additions & 1 deletion app/components/OceanInterface/OceanInterface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ActivityIndicator, Animated, Linking, TouchableOpacity, View } from 're
import { useDispatch, useSelector } from 'react-redux'
import { Text } from '..'
import { Logging } from '../../api'
import { useWalletAddressContext } from '../../contexts/WalletAddressContext'
import { useWallet } from '../../contexts/WalletContext'
import { useWhaleApiClient } from '../../contexts/WhaleContext'
import { getEnvironment } from '../../environment'
Expand Down Expand Up @@ -87,11 +88,11 @@ export function OceanInterface (): JSX.Element | null {
const { height, err: e } = useSelector((state: RootState) => state.ocean)
const transaction = useSelector((state: RootState) => firstTransactionSelector(state.ocean))
const slideAnim = useRef(new Animated.Value(0)).current
const address = useSelector((state: RootState) => state.wallet.address)
// state
const [tx, setTx] = useState<OceanTransaction | undefined>(transaction)
const [err, setError] = useState<Error | undefined>(e)
const [txid, setTxid] = useState<string | undefined>()
const { address } = useWalletAddressContext()

const dismissDrawer = useCallback(() => {
setTx(undefined)
Expand Down
38 changes: 38 additions & 0 deletions app/contexts/WalletAddressContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React, { createContext, useContext, useEffect, useState } from 'react'
import { Logging } from '../api'
import { useWallet } from './WalletContext'

interface WalletAddress {
address: string
}

const WalletAddressContext = createContext<WalletAddress>(undefined as any)

export function useWalletAddressContext (): WalletAddress {
return useContext(WalletAddressContext)
}

export function WalletAddressProvider (props: React.PropsWithChildren<any>): JSX.Element | null {
const wallet = useWallet()
const [address, setAddress] = useState<string>()

useEffect(() => {
wallet.get(0).getAddress().then(value => {
setAddress(value)
}).catch(Logging.error)
}, [])

if (address === undefined) {
return null
}

const context: WalletAddress = {
address
}

return (
<WalletAddressContext.Provider value={context}>
{props.children}
</WalletAddressContext.Provider>
)
}
3 changes: 2 additions & 1 deletion app/hooks/wallet/TokensAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { WhaleApiClient } from '@defichain/whale-api-client'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Dispatch } from 'redux'
import { useWalletAddressContext } from '../../contexts/WalletAddressContext'
import { useWhaleApiClient } from '../../contexts/WhaleContext'
import { RootState } from '../../store'
import { tokensSelector, wallet, WalletToken } from '../../store/wallet'
Expand All @@ -25,7 +26,7 @@ export function fetchTokens (client: WhaleApiClient, address: string, dispatch:
export function useTokensAPI (): WalletToken[] {
const client = useWhaleApiClient()
const tokens = useSelector((state: RootState) => tokensSelector(state.wallet))
const address = useSelector((state: RootState) => state.wallet.address)
const { address } = useWalletAddressContext()
const dispatch = useDispatch()

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,18 @@ jest.mock("../../../../hooks/wallet/TokensAPI", () => ({
}]
}));

jest.mock("../../../../contexts/WalletAddressContext", () => ({
useWalletAddressContext: () => {
return {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d'
}
}
}));

describe('balances page', () => {
it('should match snapshot', async () => {
const initialState: Partial<RootState> = {
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand All @@ -69,7 +76,6 @@ describe('balances page', () => {
/*it.skip('should display navigation buttons', async () => {
const initialState: Partial<RootState> = {
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand Down Expand Up @@ -97,7 +103,6 @@ describe('balances page', () => {
it('should navigate to token detail page', async () => {
const initialState: Partial<RootState> = {
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand Down
6 changes: 3 additions & 3 deletions app/screens/AppNavigator/screens/Balances/BalancesScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import { FlatList, RefreshControl, TouchableOpacity } from 'react-native'
import NumberFormat from 'react-number-format'
import { useDispatch, useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { Text, View } from '../../../../components'
import { getTokenIcon } from '../../../../components/icons/tokens/_index'
import { SectionTitle } from '../../../../components/SectionTitle'
import { useWalletAddressContext } from '../../../../contexts/WalletAddressContext'
import { useWhaleApiClient } from '../../../../contexts/WhaleContext'
import { fetchTokens, useTokensAPI } from '../../../../hooks/wallet/TokensAPI'
import { RootState } from '../../../../store'
import { ocean } from '../../../../store/ocean'
import { WalletToken } from '../../../../store/wallet'
import { tailwind } from '../../../../tailwind'
Expand All @@ -23,7 +23,7 @@ type Props = StackScreenProps<BalanceParamList, 'BalancesScreen'>
export function BalancesScreen ({ navigation }: Props): JSX.Element {
const height = useBottomTabBarHeight()
const client = useWhaleApiClient()
const address = useSelector((state: RootState) => state.wallet.address)
const { address } = useWalletAddressContext()
const [refreshing, setRefreshing] = useState(false)
const dispatch = useDispatch()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ import { RootState } from "../../../../../store";
import { wallet } from "../../../../../store/wallet";
import { ReceiveScreen } from "./ReceiveScreen";

jest.mock("../../../../../contexts/WalletAddressContext", () => ({
useWalletAddressContext: () => {
return {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d'
}
}
}));

jest.mock("expo-clipboard", () => ({
setString: jest.fn()
}))
Expand All @@ -15,7 +23,6 @@ describe('receive page', () => {
it('should match snapshot', async () => {
const initialState: Partial<RootState> = {
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand All @@ -36,7 +43,6 @@ describe('receive page', () => {
it('should trigger copy', async () => {
const initialState: Partial<RootState> = {
wallet: {
address: 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d',
utxoBalance: '77',
tokens: []
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import * as Clipboard from 'expo-clipboard'
import React from 'react'
import { TouchableOpacity, View } from 'react-native'
import QRCode from 'react-native-qrcode-svg'
import { useSelector } from 'react-redux'
import { Text } from '../../../../../components'
import { RootState } from '../../../../../store'
import { useWalletAddressContext } from '../../../../../contexts/WalletAddressContext'
import { tailwind } from '../../../../../tailwind'
import { translate } from '../../../../../translations'

export function ReceiveScreen (): JSX.Element {
const address = useSelector((state: RootState) => state.wallet.address)
const { address } = useWalletAddressContext()

const copyToClipboard = (text: string): void => {
Clipboard.setString(text)
Expand Down
3 changes: 2 additions & 1 deletion app/screens/AppNavigator/screens/Dex/DexScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { useDispatch, useSelector } from 'react-redux'
import { Text, View } from '../../../../components'
import { getTokenIcon } from '../../../../components/icons/tokens/_index'
import { SectionTitle } from '../../../../components/SectionTitle'
import { useWalletAddressContext } from '../../../../contexts/WalletAddressContext'
import { useWhaleApiClient } from '../../../../contexts/WhaleContext'
import { fetchTokens } from '../../../../hooks/wallet/TokensAPI'
import { RootState } from '../../../../store'
Expand All @@ -19,7 +20,7 @@ import { DexParamList } from './DexNavigator'

export function DexScreen (): JSX.Element {
const client = useWhaleApiClient()
const address = useSelector((state: RootState) => state.wallet.address)
const { address } = useWalletAddressContext()
const [pairs, setPairs] = useState<Array<DexItem<PoolPairData>>>([])
const dispatch = useDispatch()
const navigation = useNavigation<NavigationProp<DexParamList>>()
Expand Down
31 changes: 23 additions & 8 deletions app/screens/PlaygroundNavigator/sections/PlaygroundUTXO.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { Text, View } from '../../../components'
import { usePlaygroundContext } from '../../../contexts/PlaygroundContext'
import { useWallet } from '../../../contexts/WalletContext'
import { useWhaleApiClient } from '../../../contexts/WhaleContext'
import { fetchTokens } from '../../../hooks/wallet/TokensAPI'
import { tailwind } from '../../../tailwind'
import { PlaygroundAction } from '../components/PlaygroundAction'
import { PlaygroundStatus } from '../components/PlaygroundStatus'

export function PlaygroundUTXO (): JSX.Element {
const wallet = useWallet()
const whaleApiClient = useWhaleApiClient()
const dispatch = useDispatch()
const { api, rpc } = usePlaygroundContext()
const [status, setStatus] = useState<string>('loading')

Expand All @@ -33,14 +38,24 @@ export function PlaygroundUTXO (): JSX.Element {
</View>

{status === 'online' ? (
<PlaygroundAction
testID='playground_wallet_top_up'
title='Top up 10 DFI UTXO to Wallet'
onPress={async () => {
const address = await wallet.get(0).getAddress()
await rpc.wallet.sendToAddress(address, 10)
}}
/>
<>
<PlaygroundAction
testID='playground_wallet_top_up'
title='Top up 10 DFI UTXO to Wallet'
onPress={async () => {
const address = await wallet.get(0).getAddress()
await rpc.wallet.sendToAddress(address, 10)
}}
/>
<PlaygroundAction
testID='playground_wallet_fetch_balances'
title='Fetch Balances'
onPress={async () => {
const address = await wallet.get(0).getAddress()
fetchTokens(whaleApiClient, address, dispatch)
}}
/>
</>
) : null}
</View>
)
Expand Down
13 changes: 0 additions & 13 deletions app/screens/PlaygroundNavigator/sections/PlaygroundWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import { generateMnemonicWords } from '@defichain/jellyfish-wallet-mnemonic'
import * as Random from 'expo-random'
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { MnemonicUnprotected } from '../../../api/wallet'
import { Text, View } from '../../../components'
import { useNetworkContext } from '../../../contexts/NetworkContext'
import { useWalletPersistenceContext } from '../../../contexts/WalletPersistenceContext'
import { useWhaleApiClient } from '../../../contexts/WhaleContext'
import { fetchTokens } from '../../../hooks/wallet/TokensAPI'
import { RootState } from '../../../store'
import { tailwind } from '../../../tailwind'
import { PlaygroundAction } from '../components/PlaygroundAction'
import { PlaygroundStatus } from '../components/PlaygroundStatus'

export function PlaygroundWallet (): JSX.Element | null {
const { wallets, clearWallets, setWallet } = useWalletPersistenceContext()
const network = useNetworkContext()
const whaleApiClient = useWhaleApiClient()
const dispatch = useDispatch()
const address = useSelector((state: RootState) => state.wallet.address)

return (
<View>
Expand Down Expand Up @@ -56,12 +49,6 @@ export function PlaygroundWallet (): JSX.Element | null {
await setWallet(MnemonicUnprotected.toData(words, network.network))
}}
/>

<PlaygroundAction
testID='playground_wallet_fetch_balances'
title='Fetch Balances'
onPress={() => fetchTokens(whaleApiClient, address, dispatch)}
/>
</View>
)
}
31 changes: 3 additions & 28 deletions app/screens/RootNavigator.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import React, { PropsWithChildren, useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { Logging } from '../api'
import { useWallet, WalletProvider } from '../contexts/WalletContext'
import React from 'react'
import { WalletAddressProvider } from '../contexts/WalletAddressContext'
import { WalletProvider } from '../contexts/WalletContext'
import { useWalletPersistenceContext } from '../contexts/WalletPersistenceContext'
import { wallet as store } from '../store/wallet'
import { AppNavigator } from './AppNavigator/AppNavigator'
import { WalletNavigator } from './WalletNavigator/WalletNavigator'

Expand All @@ -25,26 +23,3 @@ export function RootNavigator (): JSX.Element {
</WalletProvider>
)
}

/**
* TODO(fuxingloh): to deprecate completely
* @deprecated included for legacy reasons, moving forward address should not be set in store
*/
function WalletAddressProvider (props: PropsWithChildren<any>): JSX.Element | null {
const wallet = useWallet()
const dispatch = useDispatch()
const [isLoaded, setLoaded] = useState(false)

useEffect(() => {
wallet.get(0).getAddress().then(address => {
dispatch(store.actions.setAddress(address))
setLoaded(true)
}).catch(Logging.error)
}, [wallet])

if (!isLoaded) {
return null
}

return props.children
}
8 changes: 0 additions & 8 deletions app/store/wallet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ describe('wallet reducer', () => {
initialState = {
tokens: [],
utxoBalance: '0',
address: ''
};
tokenDFI = {
id: '0',
Expand All @@ -35,7 +34,6 @@ describe('wallet reducer', () => {
expect(wallet.reducer(undefined, { type: 'unknown' })).toEqual({
utxoBalance: '0',
tokens: [],
address: ''
});
});

Expand All @@ -51,12 +49,6 @@ describe('wallet reducer', () => {
expect(actual.utxoBalance).toStrictEqual(utxoAmount)
});

it('should handle setAddress', () => {
const address = 'bcrt1q6np0fh47ykhznjhrtfvduh73cgjg32yac8t07d'
const actual = wallet.reducer(initialState, wallet.actions.setAddress(address));
expect(actual.address).toStrictEqual(address)
});

it('should able to select tokens with default DFIs', () => {
const actual = tokensSelector({ ...initialState, utxoBalance: '77' })
expect(actual).toStrictEqual([{ ...utxoDFI, amount: '77' }, { ...tokenDFI, amount: '0' }])
Expand Down
Loading