Skip to content

Commit

Permalink
feat: optimization widget
Browse files Browse the repository at this point in the history
  • Loading branch information
junjieit committed Oct 15, 2024
1 parent 904be67 commit 1a753e7
Show file tree
Hide file tree
Showing 25 changed files with 256 additions and 89 deletions.
4 changes: 2 additions & 2 deletions packages/dodoex-api/src/gql/gql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const documents = {
types.FetchLiquidityPositionsDocument,
'\n query FetchUserSwapOrderHistories($where: User_swapswapFilter) {\n user_swap_orderHistories(where: $where) {\n count\n page\n list {\n chainId\n createdAt\n fromAmount\n fromTokenDecimals\n fromTokenPrice\n fromTokenSymbol\n fromTokenAddress\n fromTokenLogoImg\n hash\n status\n toAmount\n toTokenDecimals\n toTokenPrice\n toTokenSymbol\n toTokenAddress\n toTokenLogoImg\n minAmount\n nonce\n extra\n user\n }\n }\n }\n ':
types.FetchUserSwapOrderHistoriesDocument,
'\n query FetchNoticeCenterTransactionList(\n $where: Notice_centertransactionListFilter\n ) {\n notice_center_transactionList(where: $where) {\n list {\n chainId\n createTime\n extend\n from\n id\n key\n type\n }\n count\n }\n }\n ':
'\n query FetchNoticeCenterTransactionList(\n $where: Notice_centertransactionListFilter\n ) {\n notice_center_transactionList(where: $where) {\n list {\n chainId\n createTime\n extend\n from\n id\n key\n type\n }\n count\n limit\n page\n }\n }\n ':
types.FetchNoticeCenterTransactionListDocument,
};

Expand Down Expand Up @@ -124,7 +124,7 @@ export function graphql(
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function graphql(
source: '\n query FetchNoticeCenterTransactionList(\n $where: Notice_centertransactionListFilter\n ) {\n notice_center_transactionList(where: $where) {\n list {\n chainId\n createTime\n extend\n from\n id\n key\n type\n }\n count\n }\n }\n ',
source: '\n query FetchNoticeCenterTransactionList(\n $where: Notice_centertransactionListFilter\n ) {\n notice_center_transactionList(where: $where) {\n list {\n chainId\n createTime\n extend\n from\n id\n key\n type\n }\n count\n limit\n page\n }\n }\n ',
): typeof import('./graphql').FetchNoticeCenterTransactionListDocument;

export function graphql(source: string) {
Expand Down
4 changes: 4 additions & 0 deletions packages/dodoex-api/src/gql/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23236,6 +23236,8 @@ export type FetchNoticeCenterTransactionListQueryVariables = Exact<{
export type FetchNoticeCenterTransactionListQuery = {
notice_center_transactionList?: {
count?: number | null;
limit?: number | null;
page?: number | null;
list?: Array<{
chainId?: number | null;
createTime?: string | null;
Expand Down Expand Up @@ -23929,6 +23931,8 @@ export const FetchNoticeCenterTransactionListDocument =
type
}
count
limit
page
}
}
`) as unknown as TypedDocumentString<
Expand Down
18 changes: 13 additions & 5 deletions packages/dodoex-api/src/helper/GraphQLRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import crossFetch from 'cross-fetch';
import { GraphQLClient, RequestDocument, Variables } from 'graphql-request';
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { TypedDocumentString } from '../gql/graphql';
import { GraphQLClientRequestHeaders } from 'graphql-request/build/esm/types';

type Fetch = typeof crossFetch;

export interface GraphQLRequestsConfig {
url?: string;
fetch?: Fetch;
getHeaders?: () => GraphQLClientRequestHeaders;
}

const defaultConfig = {
Expand All @@ -17,9 +19,11 @@ const defaultConfig = {
export default class GraphQLRequests {
private url: string;
private client: GraphQLClient;
private getHeaders?: GraphQLRequestsConfig['getHeaders'];
constructor(configProps?: GraphQLRequestsConfig) {
const config = { ...defaultConfig, ...configProps };
this.url = config.url;
this.getHeaders = config.getHeaders;
const client = new GraphQLClient(this.url, {
fetch: config.fetch,
requestMiddleware: (request) => {
Expand All @@ -33,18 +37,22 @@ export default class GraphQLRequests {
};
},
});
const auth =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjMxMzg2NDYzMzAzMjMxNjQzNzM5NjIzMTM4Mzk2MjJkMzA2MjYzMzkzMDYxMzc2NjM4NjQzNDMxMzYzMTJkMzEzNjM0MzYzMjYzMzY2NjJkMzE2NjYxMzQzMDMwMmQzMTM4NjQ2MzMwMzIzMTY0MzczOTYzNjI2MjYzIiwicyI6NDAsImlhdCI6MTcwODMyNzg4OSwiZXhwIjoxNzA4NDE0Mjg5fQ.S6uFXnNWL64nGj23AHuWBV7fxJ0DGlpHXoZAZXtA_Zs';
client.setHeaders({
'Access-Token': auth,
});
this.client = client;
this.setHeaders();
}

setHeaders() {
const headers = this.getHeaders?.();
if (headers) {
this.client.setHeaders(headers);
}
}

async getData<T, V extends Variables = Variables>(
document: RequestDocument | TypedDocumentNode<T, V>,
variables?: V,
) {
this.setHeaders();
const client = this.client;
// @ts-ignore
return client.request<T, V>(document, variables);
Expand Down
2 changes: 1 addition & 1 deletion packages/dodoex-api/src/services/TokenApi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,9 @@ export class TokenApi {
'token',
'getFetchTokenQuery',
chainId ?? '',
address?.toLocaleLowerCase(),
account?.toLocaleLowerCase(),
proxyContractAddress?.toLocaleLowerCase(),
address?.toLocaleLowerCase(),
],
enabled: !!chainId && !!address && !!account,
queryFn: async () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/dodoex-api/src/services/system/graphqlQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const systemGraphqlQuery = {
type
}
count
limit
page
}
}
`),
Expand Down
1 change: 1 addition & 0 deletions packages/dodoex-components/src/Lottie/EmptyDataIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default function EmptyDataIcon({
display: 'inline-block',
width: 105,
height: 105,
borderRadius: 24,
...sx,
}}
/>
Expand Down
2 changes: 1 addition & 1 deletion packages/dodoex-components/src/Tabs/TabPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Box, BoxProps } from '../Box';
import React from 'react';

export const TabPanel = React.forwardRef(function TabPanel(
props: TabPanelProps & {
props: Partial<TabPanelProps> & {
sx?: BoxProps['sx'];
},
ref,
Expand Down
2 changes: 1 addition & 1 deletion packages/dodoex-components/src/Tabs/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const Tabs = React.forwardRef(function TabsList(
{
onChange,
...props
}: TabsProps & {
}: Partial<TabsProps> & {
sx?: BoxProps['sx'];
},
ref: React.ForwardedRef<HTMLDivElement>,
Expand Down
1 change: 1 addition & 0 deletions packages/dodoex-widgets/src/components/CardWidgets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export function CardStatus({
display: 'flex',
flexDirection: 'column',
gap: 24,
px: 20,
}}
>
{increaseArray(4).map((_, i) => (
Expand Down
4 changes: 3 additions & 1 deletion packages/dodoex-widgets/src/components/Confirm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type ConfirmProps = React.PropsWithChildren<{
confirmLoading?: boolean;
isManualClose?: boolean;
onConfirm?: () => void;
modal?: boolean;
}>;
export default function Confirm(props: ConfirmProps) {
const { ConfirmComponent } = useUserOptions();
Expand All @@ -39,10 +40,11 @@ export default function Confirm(props: ConfirmProps) {
confirmLoading,
isManualClose,
onConfirm,
modal,
} = props;

return (
<Dialog open={open} onClose={onClose} title={title}>
<Dialog open={open} onClose={onClose} title={title} modal={modal}>
<Box
sx={{
display: 'flex',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ export default function SwapOrderHistory({
const theme = useTheme();
const { onlyChainId } = useUserOptions();
const { isMobile } = useWidgetDevice();
// const { account } = useWeb3React();
const account = '0x1033dd8fECCe8F5FDd4B2F235B047CB1EE59512a';
const { account } = useWeb3React();
const [filterChainId, setFilterChainId] =
React.useState<ChainId | undefined>();
const swapOrderListQueryLocal = useTradeSwapOrderList({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export function TokenPickerDialog({
modal?: boolean;
}) {
const { height } = useUserOptions();
const { isMobile } = useWidgetDevice();
return (
<Dialog
height={modal ? '80vh' : height}
Expand All @@ -63,7 +64,7 @@ export function TokenPickerDialog({
sx={
modal
? {
width: 420,
width: isMobile ? '100%' : 420,
borderRadius: 16,
}
: undefined
Expand Down
6 changes: 5 additions & 1 deletion packages/dodoex-widgets/src/components/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ export default function Table({
width: '100%',
borderCollapse: 'collapse',
'& th': {
p: 24,
py: 14,
px: 24,
typography: 'body1',
textAlign: 'left',
color: 'text.secondary',
Expand Down Expand Up @@ -62,6 +63,9 @@ export default function Table({
)} -2px 0px 4px 0px`,
},
},
'& tbody tr:hover td': {
backgroundColor: 'hover.default',
},
}}
>
{children}
Expand Down
6 changes: 4 additions & 2 deletions packages/dodoex-widgets/src/components/Widget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ function InitStatus(props: PropsWithChildren<WidgetProps>) {
ref={widgetRef}
>
<OpenConnectWalletInfo />
<WithExecutionDialog {...props}>{props.children}</WithExecutionDialog>
{props.children}
</Box>
);
}
Expand All @@ -208,7 +208,9 @@ function Web3Provider(props: PropsWithChildren<WidgetProps>) {

return (
<Web3ReactProvider connectors={connectors} key={key} lookupENS={false}>
<InitStatus {...props} />
<WithExecutionDialog {...props}>
<InitStatus {...props} />
</WithExecutionDialog>
</Web3ReactProvider>
);
}
Expand Down
110 changes: 110 additions & 0 deletions packages/dodoex-widgets/src/hooks/Token/useHasBalanceTokenList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { basicTokenMap, ChainId } from '@dodoex/api';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import BigNumber from 'bignumber.js';
import { isEqualWith } from 'lodash';
import React from 'react';
import { useSelector } from 'react-redux';
import { tokenApi } from '../../constants/api';
import { RootState } from '../../store/reducers';
import { getPopularTokenList, getTokenList } from '../../store/selectors/token';
import useTokenListFetchBalance from './useTokenListFetchBalance';

type TokenResult = NonNullable<
Awaited<ReturnType<ReturnType<typeof tokenApi.getFetchTokenQuery>['queryFn']>>
>;

export function useHasBalanceTokenList({
account,
chainId,
visible,
}: {
account: string | undefined;
chainId: ChainId | undefined;
visible?: boolean;
}) {
const queryClient = useQueryClient();
const [hasBalanceTokenList, setHasBalanceTokenList] = React.useState<
TokenResult[]
>([]);
const [hasTokenLoading, setHasTokenLoading] = React.useState(true);

const tokenList = useSelector(getTokenList);
const popularTokenList = useSelector((state: RootState) =>
getPopularTokenList(chainId ?? 1, state),
);
useTokenListFetchBalance({
chainId: chainId ?? 1,
tokenList,
popularTokenList,
visible: !!chainId && !!visible,
});

const basicToken = chainId ? basicTokenMap[chainId] : null;
useQuery(tokenApi.getFetchTokenQuery(chainId, basicToken?.address, account));

React.useEffect(() => {
let time: NodeJS.Timeout;
const commonKey = tokenApi
.getFetchTokenQuery(chainId, undefined, account)
.queryKey.filter((item) => !!item);
const unSubscribe = queryClient.getQueryCache().subscribe((event) => {
try {
const isNotMatch = commonKey.some(
(key) => !event.query.queryKey.includes(key),
);
if (!isNotMatch) {
clearTimeout(time);
// 避免频繁调用
time = setTimeout(() => {
const tokenQueriesData = queryClient.getQueriesData<TokenResult>({
queryKey: commonKey,
});
let newHasBalanceTokenList = [] as TokenResult[];
const hasBalanceAddressSet = new Set<string>();
tokenQueriesData.forEach((value) => {
const token = value[1];
if (
token &&
token.balance?.gt(0) &&
!hasBalanceAddressSet.has(token.address)
) {
hasBalanceAddressSet.add(token.address);
newHasBalanceTokenList.push(token);
}
});
newHasBalanceTokenList = newHasBalanceTokenList.sort((a, b) =>
a.balance.gt(b.balance) ? -1 : 1,
);
if (
!isEqualWith(
newHasBalanceTokenList,
hasBalanceTokenList,
(newValue, oldValue, key) => {
if (key === 'balance' && BigNumber.isBigNumber(newValue)) {
return newValue.isEqualTo(oldValue);
}
return undefined;
},
)
) {
setHasBalanceTokenList(newHasBalanceTokenList);
if (newHasBalanceTokenList.length) {
setHasTokenLoading(false);
}
}
}, 100);
}
} catch (error) {}
});

return () => {
unSubscribe();
clearTimeout(time);
};
}, [queryClient, account, chainId, hasBalanceTokenList]);

return {
tokenLoading: hasTokenLoading,
hasBalanceTokenList,
};
}
7 changes: 6 additions & 1 deletion packages/dodoex-widgets/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ export { WIDGET_MODULE_CLASS_NAME } from './components/WidgetContainer';
export type { WidgetProps } from './components/Widget';
export type SwapWidgetProps = WidgetProps & SwapProps;
export type { TokenInfo } from './hooks/Token/type';
export { useHasBalanceTokenList } from './hooks/Token/useHasBalanceTokenList';
export { useMessageState } from './hooks/useMessageState';
export { Swap } from './components/Swap';
export { default as SwapOrderHistory } from './components/Swap/SwapOrderHistory';
export { useTradeSwapOrderList } from './hooks/Swap/useTradeSwapOrderList';
export { TokenCard } from './components/Swap/components/TokenCard';
export { Pool } from './widgets/PoolWidget';
export {
default as PoolOperateDialog,
Expand All @@ -27,6 +28,10 @@ export type { PoolOperateProps } from './widgets/PoolWidget/PoolOperate';
export { usePoolBalanceInfo } from './widgets/PoolWidget/hooks/usePoolBalanceInfo';
export { MiningList } from './widgets/MiningWidget/MiningList';

export { TokenCard } from './components/Swap/components/TokenCard';
export { default as TokenLogo } from './components/TokenLogo';
export { FailedList } from './components/List/FailedList';
export { EmptyList } from './components/List/EmptyList';
export { getEtherscanPage } from './utils/address';
export {
formatReadableNumber,
Expand Down
Loading

0 comments on commit 1a753e7

Please sign in to comment.