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

Refactor SendTo - extract code to render from / to addresses into separate component #6266

Merged
merged 14 commits into from
May 4, 2023
61 changes: 61 additions & 0 deletions app/components/Views/SendFlow/AddressFrom/AddressFrom.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React from 'react';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';

import { render } from '@testing-library/react-native';

import Engine from '../../../../core/Engine';
import SendFlowAddressFrom from './';

Engine.init({});
jest.mock('@react-navigation/native', () => ({
useNavigation: () => ({
navigation: {},
}),
createNavigatorFactory: () => ({}),
}));

const initialState = {
settings: {},
engine: {
backgroundState: {
AccountTrackerController: {
accounts: {
'0x0': {
balance: 200,
},
},
},
PreferencesController: {
selectedAddress: '0x0',
identities: {
'0x0': {
address: '0x0',
name: 'Account 1',
},
},
},
},
},
};

jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest
.fn()
.mockImplementation((callback) => callback(initialState)),
}));

const mockStore = configureMockStore();
const store = mockStore(initialState);

describe('SendFlowAddressFrom', () => {
it('should render correctly', () => {
const wrapper = render(
<Provider store={store}>
<SendFlowAddressFrom fromAccountBalanceState={() => undefined} />
</Provider>,
);
expect(wrapper).toMatchSnapshot();
});
});
108 changes: 108 additions & 0 deletions app/components/Views/SendFlow/AddressFrom/AddressFrom.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { hexToBN } from '@metamask/controller-utils';
import { useNavigation } from '@react-navigation/native';

import { setSelectedAsset } from '../../../../actions/transaction';
import Routes from '../../../../constants/navigation/Routes';
import {
selectNetwork,
selectTicker,
} from '../../../../selectors/networkController';
import { doENSReverseLookup } from '../../../../util/ENSUtils';
import { renderFromWei } from '../../../../util/number';
import { getEther, getTicker } from '../../../../util/transactions';
import { AddressFrom } from '../../../UI/AddressInputs';
import { SFAddressFromProps } from './AddressFrom.types';

const SendFlowAddressFrom = ({
fromAccountBalanceState,
}: SFAddressFromProps) => {
const navigation = useNavigation();
const identities = useSelector(
(state: any) =>
state.engine.backgroundState.PreferencesController.identities,
);

const accounts = useSelector(
(state: any) =>
state.engine.backgroundState.AccountTrackerController.accounts,
);

const network = useSelector((state: any) => selectNetwork(state));
const ticker = useSelector(selectTicker);

const selectedAddress = useSelector(
(state: any) =>
state.engine.backgroundState.PreferencesController.selectedAddress,
);

const [accountAddress, setAccountAddress] = useState(selectedAddress);
const [accountName, setAccountName] = useState(
identities[selectedAddress].name,
);
const [accountBalance, setAccountBalance] = useState('');

useEffect(() => {
async function getAccount() {
const ens = await doENSReverseLookup(selectedAddress, network);
const balance = `${renderFromWei(
accounts[selectedAddress].balance,
)} ${getTicker(ticker)}`;
const balanceIsZero = hexToBN(accounts[selectedAddress].balance).isZero();
setAccountName(ens || identities[selectedAddress].name);
setAccountBalance(balance);
fromAccountBalanceState(balanceIsZero);
}
getAccount();
}, [
accounts,
selectedAddress,
ticker,
network,
identities,
fromAccountBalanceState,
]);

const dispatch = useDispatch();

const selectedAssetAction = (selectedAsset: any) =>
dispatch(setSelectedAsset(selectedAsset));

const onSelectAccount = async (address: string) => {
const { name } = identities[address];
const balance = `${renderFromWei(accounts[address].balance)} ${getTicker(
ticker,
)}`;
const ens = await doENSReverseLookup(address);
const accName = ens || name;
const balanceIsZero = hexToBN(accounts[address].balance).isZero();
selectedAssetAction(getEther(ticker));
setAccountAddress(address);
setAccountName(accName);
setAccountBalance(balance);
fromAccountBalanceState(balanceIsZero);
};

const openAccountSelector = () => {
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.SHEET.ACCOUNT_SELECTOR,
params: {
isSelectOnly: true,
onSelectAccount,
},
});
};

return (
<AddressFrom
onPressIcon={openAccountSelector}
fromAccountAddress={accountAddress}
fromAccountName={accountName}
fromAccountBalance={accountBalance}
/>
);
};

export default SendFlowAddressFrom;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface SFAddressFromProps {
fromAccountBalanceState: (value: boolean) => void;
}

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions app/components/Views/SendFlow/AddressFrom/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './AddressFrom';
76 changes: 76 additions & 0 deletions app/components/Views/SendFlow/AddressTo/AddressTo.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React from 'react';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';

import { render } from '@testing-library/react-native';

import Engine from '../../../../core/Engine';
import SendFlowAddressTo from './';

Engine.init({});
jest.mock('@react-navigation/native', () => ({
useNavigation: () => ({
navigation: {},
}),
createNavigatorFactory: () => ({}),
}));

const initialState = {
settings: {},
engine: {
backgroundState: {
AccountTrackerController: {
accounts: {
'0x0': {
balance: 200,
},
},
},
AddressBookController: {
addressBook: {},
},
PreferencesController: {
selectedAddress: '0x0',
identities: {
'0x0': {
address: '0x0',
name: 'Account 1',
},
},
},
},
},
};

const mockStore = configureMockStore();
const store = mockStore(initialState);

jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest
.fn()
.mockImplementation((callback) => callback(initialState)),
}));

describe('SendFlowAddressTo', () => {
it('should render correctly', () => {
const wrapper = render(
<Provider store={store}>
<SendFlowAddressTo
inputRef={undefined}
highlighted={false}
addressToReady={false}
toSelectedAddress={undefined}
toSelectedAddressName={undefined}
onSubmit={() => undefined}
inputWidth={undefined}
confusableCollectionArray={undefined}
isFromAddressBook={undefined}
updateParentState={undefined}
onToSelectedAddressChange={undefined}
/>
</Provider>,
);
expect(wrapper).toMatchSnapshot();
});
});
115 changes: 115 additions & 0 deletions app/components/Views/SendFlow/AddressTo/AddressTo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import React from 'react';
import { Alert } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';

import { useNavigation } from '@react-navigation/native';

import { strings } from '../../../../../locales/i18n';
import { showAlert } from '../../../../actions/alert';
import { NetworkSwitchErrorType } from '../../../../constants/error';
import Routes from '../../../../constants/navigation/Routes';
import Engine from '../../../../core/Engine';
import { selectNetwork } from '../../../../selectors/networkController';
import { handleNetworkSwitch } from '../../../../util/networks';
import { AddressTo } from '../../../UI/AddressInputs';
import { createQRScannerNavDetails } from '../../QRScanner';
import { SFAddressToProps } from './AddressTo.types';

const SendFlowAddressTo = ({
addressToReady,
confusableCollectionArray,
highlighted,
inputRef,
inputWidth,
isFromAddressBook,
onSubmit,
onToSelectedAddressChange,
toSelectedAddress,
toSelectedAddressName,
updateParentState,
}: SFAddressToProps) => {
const navigation = useNavigation();
const dispatch = useDispatch();

const network = useSelector(selectNetwork);

const frequentRpcList = useSelector(
(state: any) =>
state.engine.backgroundState.PreferencesController.frequentRpcList,
);

const showAlertAction = (config: any) => dispatch(showAlert(config));

const onHandleNetworkSwitch = (chain_id: string) => {
try {
const { NetworkController, CurrencyRateController } = Engine.context;
const networkSwitch = handleNetworkSwitch(chain_id, frequentRpcList, {
networkController: NetworkController,
currencyRateController: CurrencyRateController,
});

if (!networkSwitch) return;

showAlertAction({
isVisible: true,
autodismiss: 5000,
content: 'clipboard-alert',
data: { msg: strings('send.warn_network_change') + network },
});
} catch (e: any) {
let alertMessage;
switch (e.message) {
case NetworkSwitchErrorType.missingNetworkId:
alertMessage = strings('send.network_missing_id');
break;
default:
alertMessage = strings('send.network_not_found_description', {
chain_id,
});
}
Alert.alert(strings('send.network_not_found_title'), alertMessage);
}
};

const onScan = () => {
navigation.navigate(
...createQRScannerNavDetails({
onScanSuccess: (meta) => {
if (meta.chain_id) {
onHandleNetworkSwitch(meta.chain_id);
}
if (meta.target_address) {
onToSelectedAddressChange(meta.target_address);
}
},
origin: Routes.SEND_FLOW.SEND_TO,
}),
);
};

const onToInputFocus = () => {
updateParentState({ highlighted: !highlighted });
};
const onClear = () => onToSelectedAddressChange();

return (
<AddressTo
inputRef={inputRef}
highlighted={highlighted}
addressToReady={addressToReady}
toSelectedAddress={toSelectedAddress}
toAddressName={toSelectedAddressName}
onToSelectedAddressChange={onToSelectedAddressChange}
onScan={onScan}
onClear={onClear}
onInputFocus={onToInputFocus}
onInputBlur={onToInputFocus}
onSubmit={onSubmit}
inputWidth={inputWidth}
confusableCollection={confusableCollectionArray}
isFromAddressBook={isFromAddressBook}
/>
);
};

export default SendFlowAddressTo;
13 changes: 13 additions & 0 deletions app/components/Views/SendFlow/AddressTo/AddressTo.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export interface SFAddressToProps {
addressToReady: boolean;
confusableCollectionArray: any;
highlighted: boolean;
inputRef: any;
inputWidth: any;
isFromAddressBook: any;
onSubmit: (address: string) => void;
onToSelectedAddressChange: any;
toSelectedAddress: any;
toSelectedAddressName: any;
updateParentState: any;
}
Loading