Skip to content

Commit

Permalink
Fixes and refactors (#209)
Browse files Browse the repository at this point in the history
* fix balance subscriptions

* reset socket when disconnected

* refactor regionx enabled

* fix api connection

* fix api status

* fix wallet disconnect
  • Loading branch information
TopETH authored Aug 9, 2024
1 parent 33c2138 commit cce8d98
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 49 deletions.
8 changes: 2 additions & 6 deletions src/components/Elements/Balance/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { Box, Typography, useTheme } from '@mui/material';

import { getBalanceString } from '@/utils/functions';
import { enableRegionX, getBalanceString } from '@/utils/functions';

import { EXPERIMENTAL } from '@/consts';
import { useAccounts } from '@/contexts/account';
import { useCoretimeApi, useRegionXApi, useRelayApi } from '@/contexts/apis';
import { useBalances } from '@/contexts/balance';
import { useNetwork } from '@/contexts/network';
import { NetworkType } from '@/models';

import styles from './index.module.scss';

Expand All @@ -34,8 +32,6 @@ export const Balance = ({
const { state: coretimeState } = useCoretimeApi();
const { state: regionxState } = useRegionXApi();

const enableRegionx = network === NetworkType.ROCOCO || EXPERIMENTAL;

const items = [
...(rcBalance
? [
Expand All @@ -57,7 +53,7 @@ export const Balance = ({
},
]
: []),
...(enableRegionx
...(enableRegionX(network)
? [
// Relay asset:
...(rxRcCurrencyBalance
Expand Down
6 changes: 3 additions & 3 deletions src/components/Elements/Selectors/ChainSelector/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ interface ChainSelectorProps {
setChain: (_: ChainType) => void;
}

import { enableRegionX } from '@/utils/functions';

import {
Kusama,
KusamaCoretime,
Expand All @@ -28,7 +30,6 @@ import {
Westend,
WestendCoretime,
} from '@/assets/networks';
import { EXPERIMENTAL } from '@/consts';
import { ApiState } from '@/contexts/apis/types';
import { useNetwork } from '@/contexts/network';

Expand All @@ -55,7 +56,6 @@ export const ChainSelector = ({ chain, setChain }: ChainSelectorProps) => {
state: { name: relayChain, apiState: relayState },
} = useRelayApi();

const enableRegionX = network === NetworkType.ROCOCO || EXPERIMENTAL;
const {
state: { name: regionXChain, apiState: regionXState },
} = useRegionXApi();
Expand All @@ -73,7 +73,7 @@ export const ChainSelector = ({ chain, setChain }: ChainSelectorProps) => {
value: ChainType.CORETIME,
loading: relayState !== ApiState.READY,
},
...(enableRegionX
...(enableRegionX(network)
? [
{
icon: RegionX,
Expand Down
39 changes: 26 additions & 13 deletions src/components/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ import Link from 'next/link';
import { useRouter } from 'next/router';
import React from 'react';

import { enableRegionX } from '@/utils/functions';

import Logo from '@/assets/logo.png';
import { EXPERIMENTAL } from '@/consts';
import { useCoretimeApi, useRegionXApi, useRelayApi } from '@/contexts/apis';
import { ApiState } from '@/contexts/apis/types';
import { useNetwork } from '@/contexts/network';
import { RenewIcon } from '@/icons';
import { NetworkType } from '@/models';

import styles from './index.module.scss';
import { StatusIndicator } from '../Elements';
Expand Down Expand Up @@ -79,17 +80,15 @@ export const Sidebar = () => {

const { network } = useNetwork();
const {
state: { apiState: relayApiState },
state: { api: relayApi, apiState: relayApiState },
} = useRelayApi();
const {
state: { apiState: coretimeApiState },
state: { api: coretimeApi, apiState: coretimeApiState },
} = useCoretimeApi();
const {
state: { apiState: regionxApiState },
state: { api: regionXApi, apiState: regionxApiState },
} = useRegionXApi();

const enableRegionX = network === NetworkType.ROCOCO || EXPERIMENTAL;

const menu = {
general: [
{
Expand Down Expand Up @@ -143,18 +142,23 @@ export const Sidebar = () => {
{
label: 'Explore the Market',
route: '/marketplace',
enabled: enableRegionX,
enabled: enableRegionX(network),
icon: <ExploreIcon />,
},
{
label: 'Orders',
route: '/orders',
enabled: enableRegionX,
enabled: enableRegionX(network),
icon: <ListOutlinedIcon />,
},
],
};

const getApiState = (api: any, state: ApiState) => {
if (!api) return ApiState.DISCONNECTED;
return state;
};

return (
<div className={styles.sidebar}>
<Box
Expand Down Expand Up @@ -203,10 +207,19 @@ export const Sidebar = () => {
))}
</Stack>
<div className={styles.statusContainer}>
<StatusIndicator state={relayApiState} label='Relay chain' />
<StatusIndicator state={coretimeApiState} label='Coretime chain' />
{enableRegionX && (
<StatusIndicator state={regionxApiState} label='RegionX chain' />
<StatusIndicator
state={getApiState(relayApi, relayApiState)}
label='Relay chain'
/>
<StatusIndicator
state={getApiState(coretimeApi, coretimeApiState)}
label='Coretime chain'
/>
{enableRegionX(network) && (
<StatusIndicator
state={getApiState(regionXApi, regionxApiState)}
label='RegionX chain'
/>
)}
</div>
</Box>
Expand Down
10 changes: 7 additions & 3 deletions src/contexts/account/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,20 @@ const AccountProvider = ({ children }: Props) => {
asyncLoadAccounts();
};

const disconnectWallet = () => dispatch({ type: 'DISCONNECT' });
const disconnectWallet = () => {
localStorage.removeItem(LOCAL_STORAGE_ACCOUNTS);
localStorage.removeItem(LOCAL_STORAGE_ACTIVE_ACCOUNT);
dispatch({ type: 'DISCONNECT' });
};

useEffect(() => {
const accounts = state.accounts;

if (accounts.length) {
const activeAccount = localStorage.getItem(LOCAL_STORAGE_ACTIVE_ACCOUNT);
const account: InjectedAccountWithMeta = activeAccount
? (accounts.find((acc: any) => acc.address == activeAccount) ??
accounts[0])
? accounts.find((acc: any) => acc.address == activeAccount) ??
accounts[0]
: accounts[0];

setActiveAccount(account);
Expand Down
2 changes: 1 addition & 1 deletion src/contexts/apis/CoretimeApi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const CoretimeApiContextProvider = (props: any) => {
}
connect(state, url, dispatch, true, types);
}
}, [network, state]);
}, [network, state.socket]);

return (
<CoretimeApiContext.Provider
Expand Down
8 changes: 5 additions & 3 deletions src/contexts/apis/RegionXApi/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React, { useContext, useEffect, useReducer } from 'react';

import { EXPERIMENTAL, WS_REGIONX_COCOS_CHAIN } from '@/consts';
import { enableRegionX } from '@/utils/functions';

import { WS_REGIONX_COCOS_CHAIN } from '@/consts';
import { useNetwork } from '@/contexts/network';
import { useToast } from '@/contexts/toast';
import { NetworkType } from '@/models';
Expand Down Expand Up @@ -109,7 +111,7 @@ const RegionXApiContextProvider = (props: any) => {
};

useEffect(() => {
if (network !== NetworkType.ROCOCO && !EXPERIMENTAL) {
if (!enableRegionX(network)) {
return;
}
const url = getUrl(network);
Expand All @@ -125,7 +127,7 @@ const RegionXApiContextProvider = (props: any) => {
}
connect(state, url, dispatch, true, types, customRpc);
}
}, [network, state]);
}, [network, state.socket]);

useEffect(() => {
dispatch({ type: 'DISCONNECTED' });
Expand Down
2 changes: 1 addition & 1 deletion src/contexts/apis/RelayApi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const RelayApiContextProvider = (props: any) => {
}
connect(state, url, dispatch, true);
}
}, [network, state]);
}, [network, state.socket]);

useEffect(() => {
const { api, apiState } = state;
Expand Down
1 change: 1 addition & 0 deletions src/contexts/apis/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export const reducer = (state: any, action: any) => {
...state,
api: null,
apiState: ApiState.DISCONNECTED,
socket: '',
symbol: '',
name: '',
height: 0,
Expand Down
13 changes: 5 additions & 8 deletions src/contexts/balance/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, { createContext, useContext, useEffect, useState } from 'react';

import { EXPERIMENTAL } from '@/consts';
import { NetworkType } from '@/models';
import { enableRegionX } from '@/utils/functions';

import { useAccounts } from '../account';
import { useCoretimeApi, useRegionXApi, useRelayApi } from '../apis';
Expand Down Expand Up @@ -47,8 +46,6 @@ const BalanceProvider = ({ children }: Props) => {
state: { api: regionxApi, apiState: regionxApiState },
} = useRegionXApi();

const enableRegionx = network === NetworkType.ROCOCO || EXPERIMENTAL;

const [coretimeBalance, setCoretimeBalance] = useState(0);
const [relayBalance, setRelayBalance] = useState(0);
const [rxNativeBalance, setRxNativeBalance] = useState(0);
Expand Down Expand Up @@ -95,7 +92,7 @@ const BalanceProvider = ({ children }: Props) => {
);
let unsubscribeRegionx: any = null;

if (enableRegionx) {
if (enableRegionX(network)) {
if (!regionxApi || regionxApiState !== ApiState.READY) return;
unsubscribeRegionx = await regionxApi.queryMulti(
[
Expand All @@ -115,8 +112,8 @@ const BalanceProvider = ({ children }: Props) => {
}

return () => {
unsubscribeCoretime();
unsubscribeRelay();
if (unsubscribeCoretime) unsubscribeCoretime();
if (unsubscribeRelay) unsubscribeRelay();
if (unsubscribeRegionx) unsubscribeRegionx();
};
};
Expand All @@ -129,7 +126,7 @@ const BalanceProvider = ({ children }: Props) => {
relayApiState,
regionxApi,
regionxApiState,
enableRegionx,
network,
]);

return (
Expand Down
7 changes: 4 additions & 3 deletions src/contexts/regions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import React, {
useState,
} from 'react';

import { EXPERIMENTAL } from '@/consts';
import { enableRegionX } from '@/utils/functions';

import {
ContextStatus,
ISMPRecordStatus,
Expand Down Expand Up @@ -118,7 +119,7 @@ const RegionDataProvider = ({ children }: Props) => {

const ctRegions = await collectCoretimeRegions(tasks);
const rxRegions =
EXPERIMENTAL || network === NetworkType.ROCOCO
enableRegionX(network)
? await collectRegionXRegions(tasks)
: [];

Expand Down Expand Up @@ -176,7 +177,7 @@ const RegionDataProvider = ({ children }: Props) => {
// Only user owned non-expired regions.
if (
encodeAddress(region.getOwner(), 42) !==
encodeAddress(activeAccount.address, 42) ||
encodeAddress(activeAccount.address, 42) ||
region.consumed({ timeslicePeriod, relayBlockNumber }) > 1
)
return null;
Expand Down
11 changes: 4 additions & 7 deletions src/pages/transfer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Region } from 'coretime-utils';
import { useRouter } from 'next/router';
import { useState } from 'react';

import { enableRegionX } from '@/utils/functions';
import theme from '@/utils/muiTheme';
import {
coretimeFromRegionXTransfer,
Expand All @@ -31,7 +32,6 @@ import {
} from '@/components';
import AssetSelector from '@/components/Elements/Selectors/AssetSelector';

import { EXPERIMENTAL } from '@/consts';
import { useAccounts } from '@/contexts/account';
import { useCoretimeApi, useRelayApi } from '@/contexts/apis';
import { useRegionXApi } from '@/contexts/apis/RegionXApi';
Expand All @@ -44,7 +44,6 @@ import {
ChainType,
CORETIME_DECIMALS,
ISMPRecordStatus,
NetworkType,
RegionLocation,
RegionMetadata,
} from '@/models';
Expand Down Expand Up @@ -86,8 +85,6 @@ const TransferPage = () => {
const [asset, setAsset] = useState<AssetType>(AssetType.TOKEN);
const [transferAmount, setTransferAmount] = useState<number | undefined>();

const enableRegionX = network === NetworkType.ROCOCO || EXPERIMENTAL;

const defaultHandler = {
ready: () => toastInfo('Transaction was initiated'),
inBlock: () => toastInfo('In Block'),
Expand Down Expand Up @@ -155,7 +152,7 @@ const TransferPage = () => {
api = relayApi;
} else {
// RegionX
if (!enableRegionX) {
if (!enableRegionX(network)) {
toastWarning('Currently not supported');
return;
}
Expand Down Expand Up @@ -239,7 +236,7 @@ const TransferPage = () => {
originChain === ChainType.CORETIME &&
destinationChain === ChainType.REGIONX
) {
if (!enableRegionX) toastWarning('Currently not supported');
if (!enableRegionX(network)) toastWarning('Currently not supported');
else {
const receiverKeypair = new Keyring();
receiverKeypair.addFromAddress(
Expand All @@ -263,7 +260,7 @@ const TransferPage = () => {
originChain === ChainType.REGIONX &&
destinationChain === ChainType.CORETIME
) {
if (!enableRegionX || !regionXApi || regionxApiState !== ApiState.READY) {
if (!enableRegionX(network) || !regionXApi || regionxApiState !== ApiState.READY) {
toastWarning('Currently not supported');
return;
}
Expand Down
7 changes: 6 additions & 1 deletion src/utils/functions/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { AddressOrPair, SubmittableExtrinsic } from '@polkadot/api/types';
import { ISubmittableResult, Signer } from '@polkadot/types/types';

import { TxStatusHandlers } from '@/models';
import { EXPERIMENTAL } from '@/consts';
import { NetworkType, TxStatusHandlers } from '@/models';

export const sendTx = async (
tx: SubmittableExtrinsic<'promise', ISubmittableResult>,
Expand Down Expand Up @@ -35,3 +36,7 @@ export const sendTx = async (
handlers.finally && handlers.finally();
}
};

export const enableRegionX = (network: NetworkType): boolean => {
return network === NetworkType.ROCOCO || EXPERIMENTAL;
};

0 comments on commit cce8d98

Please sign in to comment.