Skip to content

Commit

Permalink
working
Browse files Browse the repository at this point in the history
  • Loading branch information
Szegoo committed Apr 18, 2024
1 parent 67daeb0 commit bf2e649
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 45 deletions.
4 changes: 2 additions & 2 deletions src/components/Elements/FeatureCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const FeatureCard = ({
enabled,
href,
}: FeatureCardProps) => {
const { push } = useRouter();
const { push, query } = useRouter();

return (
<Card className={styles.card}>
Expand All @@ -38,7 +38,7 @@ export const FeatureCard = ({
</Typography>
<CardActions>
<Button
onClick={() => enabled && push(href)}
onClick={() => enabled && push({ pathname: href, query })}
size='small'
variant='text'
disabled={!enabled}
Expand Down
11 changes: 1 addition & 10 deletions src/components/Header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ import {
} from '@mui/material';
import { useInkathon } from '@scio-labs/use-inkathon';
import Image from 'next/image';
import React, { useEffect, useState } from 'react';
import React, { useState } from 'react';

import Logo from '@/assets/logo.png';
import { useCoretimeApi, useRelayApi } from '@/contexts/apis';

import styles from './index.module.scss';
import { WalletModal } from '../Modals/WalletConnect';
Expand All @@ -23,14 +22,6 @@ export const Header = () => {
const [accountsOpen, openAccounts] = useState(false);
const [walletModalOpen, openWalletModal] = useState(false);

const { connectRelay } = useRelayApi();
const { connectCoretime } = useCoretimeApi();

useEffect(() => {
connectRelay();
connectCoretime();
}, [connectRelay, connectCoretime]);

const onDisconnect = () => {
openAccounts(false);
disconnect && disconnect();
Expand Down
4 changes: 2 additions & 2 deletions src/components/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ interface MenuItemProps {
}

const MenuItem = ({ label, enabled, route, icon }: MenuItemProps) => {
const { pathname, push } = useRouter();
const { pathname, push, query } = useRouter();
const isActive = pathname === route;

return (
<Box
className={`${styles.menuItem} ${
isActive ? styles.active : styles.inactive
} ${!enabled ? styles.disabled : ''}`}
onClick={() => enabled && route && push(route)}
onClick={() => enabled && route && push({ pathname: route, query })}
>
{{
...icon,
Expand Down
16 changes: 7 additions & 9 deletions src/contexts/apis/CoretimeApi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ const types = {

const defaultValue = {
state: { ...initialState },
connectCoretime: (): void => {
/** */
},
disconnectCoretime: (): void => {
/** */
},
Expand Down Expand Up @@ -63,15 +60,16 @@ const CoretimeApiContextProvider = (props: any) => {
}
};

const connectCoretime = () =>
connect(state, getUrl(network), dispatch, types);

const disconnectCoretime = () => disconnect(state);

useEffect(() => {
if (!network || state.socket == getUrl(network)) return;
const updateNetwork = network != '' && state.socket != getUrl(network);
connect(state, getUrl(network), dispatch, updateNetwork, types);
}, [network]);

return (
<CoretimeApiContext.Provider
value={{ state, connectCoretime, disconnectCoretime }}
>
<CoretimeApiContext.Provider value={{ state, disconnectCoretime }}>
{props.children}
</CoretimeApiContext.Provider>
);
Expand Down
30 changes: 23 additions & 7 deletions src/contexts/apis/RelayApi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ import { ParaId } from '@/models';

import { connect, disconnect, initialState, reducer } from '../common';
import { WS_ROCOCO_RELAY_CHAIN, WS_KUSAMA_RELAY_CHAIN } from '../consts';
import { useRouter } from 'next/router';

const defaultValue = {
state: initialState,
connectRelay: (): void => {
/** */
},
disconnectRelay: (): void => {
/** */
},
Expand All @@ -27,6 +25,9 @@ const RelayApiContextProvider = (props: any) => {
const { toastError, toastSuccess } = useToast();
const [paraIds, setParaIds] = useState<ParaId[]>([]);

const router = useRouter();
const { network } = router.query;

useEffect(() => {
state.apiError && toastError(`Failed to connect to relay chain`);
}, [state.apiError, toastError]);
Expand All @@ -36,9 +37,26 @@ const RelayApiContextProvider = (props: any) => {
toastSuccess('Successfully connected to the relay chain');
}, [state.apiState, toastSuccess]);

const connectRelay = () => connect(state, WS_ROCOCO_RELAY_CHAIN, dispatch);
const disconnectRelay = () => disconnect(state);

const getUrl = (network: any): string => {
if (!network || network == 'rococo') {
return WS_ROCOCO_RELAY_CHAIN;
} else if (network == 'kusama') {
return WS_KUSAMA_RELAY_CHAIN;
} else {
console.error(`Network: ${network} not recognized`);
// Default to rococo.
return WS_ROCOCO_RELAY_CHAIN;
}
};

useEffect(() => {
if (!network || state.socket == getUrl(network)) return;
const updateNetwork = network != '' && state.socket != getUrl(network);
connect(state, getUrl(network), dispatch, updateNetwork);
}, [network]);

useEffect(() => {
const { api, apiState } = state;
if (!api || apiState !== ApiState.READY) return;
Expand All @@ -54,9 +72,7 @@ const RelayApiContextProvider = (props: any) => {
}, [state]);

return (
<RelayApiContext.Provider
value={{ state, connectRelay, disconnectRelay, paraIds }}
>
<RelayApiContext.Provider value={{ state, disconnectRelay, paraIds }}>
{props.children}
</RelayApiContext.Provider>
);
Expand Down
26 changes: 18 additions & 8 deletions src/contexts/apis/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { ApiState } from './types';
export type State = {
jsonrpc: Record<string, Record<string, DefinitionRpcExt>>;
api: ApiPromise | null;
socket: string;
apiError: any;
apiState: ApiState;
};
Expand All @@ -18,6 +19,7 @@ export const initialState: State = {
// These are the states
jsonrpc: { ...jsonrpc },
api: null,
socket: '',
apiError: null,
apiState: ApiState.DISCONNECTED,
};
Expand All @@ -28,9 +30,18 @@ export const initialState: State = {
export const reducer = (state: any, action: any) => {
switch (action.type) {
case 'CONNECT_INIT':
return { ...state, apiState: ApiState.CONNECT_INIT };
return {
...state,
socket: action.socket,
apiState: ApiState.CONNECT_INIT,
};
case 'CONNECT':
return { ...state, api: action.payload, apiState: ApiState.CONNECTING };
return {
...state,
socket: action.socket,
api: action.payload,
apiState: ApiState.CONNECTING,
};
case 'CONNECT_SUCCESS':
return { ...state, apiState: ApiState.READY };
case 'CONNECT_ERROR':
Expand All @@ -49,22 +60,21 @@ export const connect = (
state: any,
socket: string,
dispatch: any,
newSocket: boolean,
types?: any
) => {
const { apiState, jsonrpc } = state;
// We only want this function to be performed once
if (apiState !== ApiState.DISCONNECTED) return;

if (!socket) return;

dispatch({ type: 'CONNECT_INIT' });
// We only want this function to be performed once
if (apiState !== ApiState.DISCONNECTED && !newSocket) return;

const provider = new WsProvider(socket);
const _api = new ApiPromise({ provider, rpc: jsonrpc, types });
dispatch({ type: 'CONNECT_INIT', socket });

// Set listeners for disconnection and reconnection event.
_api.on('connected', () => {
dispatch({ type: 'CONNECT', payload: _api });
dispatch({ type: 'CONNECT', payload: _api, socket });
// `ready` event is not emitted upon reconnection and is checked explicitly here.
_api.isReady.then(() => dispatch({ type: 'CONNECT_SUCCESS' }));
});
Expand Down
2 changes: 1 addition & 1 deletion src/contexts/apis/consts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export const WS_ROCOCO_RELAY_CHAIN = process.env.WS_ROCOCO_RELAY_CHAIN ?? '';
export const WS_KUSAMA_RELAY_CHAIN = process.env.WS_ROCOCO_KUSAMA_CHAIN ?? '';
export const WS_KUSAMA_RELAY_CHAIN = process.env.WS_KUSAMA_RELAY_CHAIN ?? '';
export const WS_ROCOCO_CORETIME_CHAIN =
process.env.WS_ROCOCO_CORETIME_CHAIN ?? '';
export const WS_KUSAMA_CORETIME_CHAIN =
Expand Down
2 changes: 0 additions & 2 deletions src/contexts/regions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,6 @@ const RegionDataProvider = ({ children }: Props) => {
);
}

console.log(_regions);

setRegions(_regions);
setLoading(false);
}, [
Expand Down
9 changes: 7 additions & 2 deletions src/contexts/sales/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,15 @@ const SaleInfoProvider = ({ children }: Props) => {

const fetchSaleInfo = useCallback(async () => {
setLoading(true);
if (!coretimeApi || coretimeApiState !== ApiState.READY) return {};
if (
!coretimeApi ||
coretimeApiState !== ApiState.READY ||
!coretimeApi.query.broker
)
return {};

const saleInfo: any = (await coretimeApi.query.broker.saleInfo()).toHuman();
if (Object.keys(saleInfo).length) {
if (saleInfo && Object.keys(saleInfo).length) {
setSaleInfo({
coresOffered: parseHNString(saleInfo.coresOffered.toString()),
coresSold: parseHNString(saleInfo.coresSold.toString()),
Expand Down
14 changes: 12 additions & 2 deletions src/contexts/tasks/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ const TaskDataProvider = ({ children }: Props) => {

// The tasks which will run on Polkadot cores in the future.
const fetchWorkplan = async (): Promise<Tasks> => {
if (!coretimeApi || coretimeApiState !== ApiState.READY) return {};
if (
!coretimeApi ||
coretimeApiState !== ApiState.READY ||
!coretimeApi.query.broker
)
return {};
const workplan = await coretimeApi.query.broker.workplan.entries();
const tasks: Record<string, number | null> = {};

Expand Down Expand Up @@ -94,7 +99,12 @@ const TaskDataProvider = ({ children }: Props) => {
core: CoreIndex,
regionMask: CoreMask
): Promise<Task> => {
if (!coretimeApi || coretimeApiState !== ApiState.READY) return null;
if (
!coretimeApi ||
coretimeApiState !== ApiState.READY ||
!coretimeApi.query.broker
)
return null;
const workload = (
(
await coretimeApi.query.broker.workload(core)
Expand Down

0 comments on commit bf2e649

Please sign in to comment.