Skip to content

Commit

Permalink
feat: remove lisk-service dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
shuse2 committed Jun 3, 2024
1 parent 1c4c3d7 commit 0096965
Show file tree
Hide file tree
Showing 17 changed files with 78 additions and 394 deletions.
115 changes: 7 additions & 108 deletions setup/react/app/ApplicationBootstrap.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
/* eslint-disable complexity */
/* eslint-disable max-statements */
import React, { createContext, useEffect, useRef, useState } from 'react';
import { useTransactionUpdate } from '@transaction/hooks';
import useSettings from '@settings/hooks/useSettings';
import {
useApplicationManagement,
useCurrentApplication,
} from '@blockchainApplication/manage/hooks';
import { useNetworkStatus, useIndexStatus } from '@network/hooks/queries';
import { useBlockchainApplicationMeta } from '@blockchainApplication/manage/hooks/queries/useBlockchainApplicationMeta';
import React, { createContext } from 'react';
import { useCurrentAccount } from 'src/modules/account/hooks';
import { Client } from 'src/utils/api/client';
import { useReduxStateModifier } from 'src/utils/useReduxStateModifier';
import { useLedgerDeviceListener } from '@libs/hardwareWallet/ledger/ledgerDeviceListener/useLedgerDeviceListener';
import { useValidServiceUrl } from '@blockchainApplication/manage/hooks/useValidServiceUrl';
import { useRewardsClaimable } from 'src/modules/pos/reward/hooks/queries';

export const ApplicationBootstrapContext = createContext({
Expand All @@ -25,97 +15,8 @@ export const ApplicationBootstrapContext = createContext({
});

const ApplicationBootstrap = ({ children }) => {
const { mainChainNetwork } = useSettings('mainChainNetwork');
const [isFirstTimeLoading, setIsFirstTimeLoading] = useState(true);
const [currentApplication, setCurrentApplication] = useCurrentApplication();
const { setApplications } = useApplicationManagement();
const [currentAccount] = useCurrentAccount();
const accountAddress = currentAccount?.metadata?.address;
const queryClient = useRef();

queryClient.current = new Client({
http: mainChainNetwork?.serviceUrl,
ws: mainChainNetwork?.wsServiceUrl,
});

useTransactionUpdate();
const networkStatus = useNetworkStatus({
options: { enabled: !!mainChainNetwork },
client: queryClient.current,
});
const indexStatus = useIndexStatus({
options: {
enabled: !!mainChainNetwork,
},
client: queryClient.current,
});

const blockchainAppsMeta = useBlockchainApplicationMeta({
config: {
params: {
chainID: [...new Set([networkStatus.data?.data?.chainID, currentApplication.chainID])]
.filter((item) => item)
.join(','),
},
},
options: { enabled: !!networkStatus.data && !!mainChainNetwork },
client: queryClient.current,
});

const serviceUrls = blockchainAppsMeta.data?.data.find(
({ chainID }) => networkStatus.data?.data?.chainID === chainID
)?.serviceURLs;

const { validServiceUrl } = useValidServiceUrl(serviceUrls);

const mainChainApplication = blockchainAppsMeta.data?.data?.find(
({ chainID }) => chainID === networkStatus?.data?.data?.chainID
);

const isError =
((networkStatus.isError && !networkStatus.data) || blockchainAppsMeta.isError) &&
!!mainChainNetwork;

useEffect(() => {
if (mainChainApplication && validServiceUrl) {
const refreshedCurrentApplication = blockchainAppsMeta?.data?.data?.find(
({ chainID }) => chainID === currentApplication?.chainID
);
const networkCode = mainChainApplication.chainID.match(/^\d{4}/g)[0];
const currentAppToSelect =
refreshedCurrentApplication?.chainID?.indexOf(networkCode) === 0
? refreshedCurrentApplication
: mainChainApplication;

const currentApplicationWithValidServiceUrlAtTheTop = {
...currentAppToSelect,
serviceURLs: currentAppToSelect.serviceURLs.sort((a, b) => {
const nameA = a.http === validServiceUrl;
const nameB = b.http === validServiceUrl;
if (nameA && nameB) {
return 0;
}
if (nameA) {
return -1;
}
return 1;
}),
};

setCurrentApplication(currentApplicationWithValidServiceUrlAtTheTop);
setApplications([mainChainApplication]);
}

if (isFirstTimeLoading && blockchainAppsMeta.isFetched && !blockchainAppsMeta.isError) {
setIsFirstTimeLoading(false);
}
}, [
mainChainNetwork,
blockchainAppsMeta.isFetched,
blockchainAppsMeta.isError,
blockchainAppsMeta.isLoading,
validServiceUrl,
]);

useLedgerDeviceListener();
useReduxStateModifier();
Expand All @@ -127,14 +28,12 @@ const ApplicationBootstrap = ({ children }) => {
return (
<ApplicationBootstrapContext.Provider
value={{
queryClient,
hasNetworkError: isError && !blockchainAppsMeta.isFetching,
isLoadingNetwork:
(blockchainAppsMeta.isFetching && !blockchainAppsMeta.data) ||
(networkStatus.isFetching && !networkStatus.data),
indexStatus: indexStatus?.data?.data || {},
error: networkStatus.error || blockchainAppsMeta.error,
refetchNetwork: blockchainAppsMeta.refetch,
queryClient: {},
hasNetworkError: false,
isLoadingNetwork: false,
indexStatus: {},
error: null,
refetchNetwork: false,
appEvents: { transactions: { rewards: rewardsData?.data ?? [] } },
}}
>
Expand Down
2 changes: 0 additions & 2 deletions setup/react/app/MainRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { SIGNING_METHODS } from '@libs/wcm/constants/permissions';
import routesMap from 'src/routes/routesMap';
import NotFound from '@common/components/NotFound';
import CustomRoute from '@common/components/customRoute';
import RewardsNotification from '@common/components/notification/rewardsNotification';
import routes from 'src/routes/routes';
import styles from './app.css';

Expand Down Expand Up @@ -42,7 +41,6 @@ const MainRouter = ({ history }) => {

return (
<div className={`${styles.mainContent} ${styles.mainBox}`}>
<RewardsNotification />
<Switch>
{routesList.map((route) => (
<CustomRoute
Expand Down
22 changes: 2 additions & 20 deletions setup/react/app/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
/* istanbul ignore file */
// This is covered by e2e tests
import React, { useContext, useEffect, useState } from 'react';
import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { settingsRetrieved } from 'src/modules/settings/store/actions';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { hot } from 'react-hot-loader/root';
import { bookmarksRetrieved } from 'src/modules/bookmark/store/action';
import { watchListRetrieved } from 'src/modules/pos/validator/store/actions/watchList';
import useIpc from '@update/hooks/useIpc';
import ConnectionProvider from '@libs/wcm/context/connectionProvider';
import FlashMessageHolder from 'src/theme/flashMessage/holder';
Expand All @@ -17,12 +16,9 @@ import OfflineWrapper from 'src/modules/common/components/offlineWrapper';
import NavigationBars from 'src/modules/common/components/bars';
import ThemeContext from 'src/theme/themeProvider';
import { MOCK_SERVICE_WORKER } from 'src/const/config';
import NetworkError from 'src/modules/common/components/NetworkError/NetworkError';
import PageLoader from 'src/modules/common/components/pageLoader';
import MainRouter from './MainRouter';
import './variables.css';
import styles from './app.css';
import { ApplicationBootstrapContext } from './ApplicationBootstrap';

if (MOCK_SERVICE_WORKER) {
const { worker } = require('src/service/mock/runtime');
Expand All @@ -32,19 +28,6 @@ if (MOCK_SERVICE_WORKER) {
})();
}

const AppContent = () => {
const { hasNetworkError, refetchNetwork, error, isLoadingNetwork, indexStatus } = useContext(
ApplicationBootstrapContext
);
const { percentageIndexed, chainLength, numBlocksIndexed } = indexStatus;
const shouldShowIndexingLoader = chainLength - numBlocksIndexed >= 5;

if (isLoadingNetwork) return <PageLoader />;
if (shouldShowIndexingLoader) return <PageLoader progress={percentageIndexed} />;

return hasNetworkError ? <NetworkError onRetry={refetchNetwork} error={error} /> : <MainRouter />;
};

// eslint-disable-next-line max-statements
const App = ({ history }) => {
const dispatch = useDispatch();
Expand All @@ -57,7 +40,6 @@ const App = ({ history }) => {
setLoaded(true);
dispatch(bookmarksRetrieved());
dispatch(settingsRetrieved());
dispatch(watchListRetrieved());
}, []);

return (
Expand All @@ -79,7 +61,7 @@ const App = ({ history }) => {
<main className={`${styles.bodyWrapper} ${loaded ? styles.loaded : ''}`}>
<section className="scrollContainer">
<FlashMessageHolder />
<AppContent />
<MainRouter />
</section>
</main>
</OfflineWrapper>
Expand Down
5 changes: 0 additions & 5 deletions src/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
"Account details": "Account details",
"Account was removed": "Account was removed",
"Account(s) to use on this application": "Account(s) to use on this application",
"Accounts": "Accounts",
"Action": "Action",
"Activated": "Activated",
"Active validators": "Active validators",
Expand All @@ -28,7 +27,6 @@
"Add application": "Add application",
"Add bookmark": "Add bookmark",
"Add message (Optional)": "Add message (Optional)",
"Add network": "Add network",
"Add new": "Add new",
"Add to staking queue": "Add to staking queue",
"Add to watched": "Add to watched",
Expand Down Expand Up @@ -86,7 +84,6 @@
"Block details": "Block details",
"Block height": "Block height",
"Block status": "Block status",
"Blocks": "Blocks",
"Blocks generated": "Blocks generated",
"Blocks overview": "Blocks overview",
"Bookmarks": "Bookmarks",
Expand Down Expand Up @@ -394,7 +391,6 @@
"Multisignature params signatures": "Multisignature params signatures",
"My validator profile": "My validator profile",
"Name": "Name",
"Network": "Network",
"Network Connection Issues": "Network Connection Issues",
"Network fee": "Network fee",
"Network statistics": "Network statistics",
Expand Down Expand Up @@ -787,7 +783,6 @@
"View profile": "View profile",
"View remaining": "View remaining",
"Volume": "Volume",
"Wallet": "Wallet",
"Wallet address:": "Wallet address:",
"Wallet balance": "Wallet balance",
"Wallet connections": "Wallet connections",
Expand Down
11 changes: 0 additions & 11 deletions src/modules/account/const/accountMenu.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import routes from 'src/routes/routes';

export const accountMenu = ({
authData,
isHW,
hasNetworkError,
isLoadingNetwork,
insuffientBalanceMessage,
address,
}) => [
{
Expand All @@ -30,15 +28,6 @@ export const accountMenu = ({
icon: 'plus',
label: 'Add new account',
},
{
component: !Object.values(insuffientBalanceMessage).length
? 'multiSignature'
: 'noTokenBalance',
data: insuffientBalanceMessage,
icon: 'multiSignatureOutline',
isHidden: hasNetworkError || isLoadingNetwork,
label: `${authData?.data?.numberOfSignatures > 0 ? 'Edit' : 'Register'} multisignature account`,
},
{
component: 'removeSelectedAccount',
icon: 'removeRed',
Expand Down
4 changes: 1 addition & 3 deletions src/modules/account/hooks/useCurrentAccount.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useHistory } from 'react-router-dom';
import { toast } from 'react-toastify';
import { selectCurrentAccount } from '@account/store/selectors';
import { selectStaking } from 'src/redux/selectors';
import { stakesReset } from '@pos/validator/store/actions/staking';
import {
removeThenAppendSearchParamsToUrl,
removeSearchParamsFromUrl,
Expand All @@ -22,7 +21,6 @@ export function useCurrentAccount() {

const switchAccount = ({ encryptedAccount, relativeUrlPath, redirect, urlState }) => {
dispatch(setCurrentAccount(encryptedAccount));
dispatch(stakesReset());
toast.dismiss();
if (redirect) {
if (urlState) {
Expand All @@ -41,7 +39,7 @@ export function useCurrentAccount() {
// eslint-disable-next-line max-statements
const setAccount = (encryptedAccount, referrer, redirect = true, urlState) => {
// clear stakes list during login or accounts switch
const relativeUrlPath = referrer || routes.wallet.path;
const relativeUrlPath = referrer || routes.blockchainApplications.path;

const showConfirmAccountSwitchDialog = pendingStakes.length && !urlState;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import Box from 'src/theme/box';
import Dialog from '@theme/dialog/dialog';
import { useBlockchainApplicationMeta } from '@blockchainApplication/manage/hooks/queries/useBlockchainApplicationMeta';
import { PrimaryButton } from 'src/theme/buttons';
import { addSearchParamsToUrl } from 'src/utils/searchParams';
import { Input } from 'src/theme';
Expand All @@ -28,10 +27,7 @@ const ConnectionProposal = () => {
.join(',')
.replace(/lisk:/g, '');

const blockchainAppsMeta = useBlockchainApplicationMeta({
config: { params: { chainID: requestingChainIDs } },
options: { enabled: !!requestingChainIDs },
});
const invalidRequestChainID = requestingChainIDs !== '00000000' && requestingChainIDs !== '01000000';

// eslint-disable-next-line max-statements
const clickHandler = async () => {
Expand Down Expand Up @@ -61,14 +57,12 @@ const ConnectionProposal = () => {
// istanbul ignore else
const cleanUpFn = () => {};

if (blockchainAppsMeta.isFetching || blockchainAppsMeta.isLoading) return cleanUpFn;

const nameSpaceKeys = requiredNamespaces && Object.keys(requiredNamespaces);
const hasNameSpaceError =
!nameSpaceKeys || nameSpaceKeys.length > 1 || !nameSpaceKeys.includes('lisk');
const isSessionProposal = event?.name === EVENTS.SESSION_PROPOSAL;

if (!blockchainAppsMeta.data?.data?.length || blockchainAppsMeta.isError) {
if (invalidRequestChainID) {
setNameSpaceError(t('Connection request contains unsupported chainIDs.'));

return cleanUpFn;
Expand All @@ -82,7 +76,7 @@ const ConnectionProposal = () => {
}

return cleanUpFn;
}, [events, blockchainAppsMeta.isFetching]);
}, [events]);

const onInputChange = ({ target }) => {
setNameSpaceError('');
Expand All @@ -103,7 +97,7 @@ const ConnectionProposal = () => {
onChange={onInputChange}
value={wcUri}
className={styles.input}
isLoading={blockchainAppsMeta.isFetching}
isLoading={false}
placeholder={t('Enter connection URI')}
/>
{nameSpaceError && (
Expand All @@ -120,9 +114,7 @@ const ConnectionProposal = () => {
disabled={
nameSpaceError ||
wcUri.length === 0 ||
status.isPending ||
blockchainAppsMeta.isFetching ||
blockchainAppsMeta.isError
status.isPending
}
>
{t('Connect')}
Expand Down
Loading

0 comments on commit 0096965

Please sign in to comment.