Skip to content

Commit

Permalink
get missing token
Browse files Browse the repository at this point in the history
  • Loading branch information
GrandSchtroumpf committed Nov 7, 2024
1 parent 6dec33d commit debdf37
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 26 deletions.
108 changes: 84 additions & 24 deletions src/components/explorer/ExplorerHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,61 @@
import { TokensOverlap } from 'components/common/tokensOverlap';
import { useTokensQuery } from 'libs/queries';
import { getStrategyType } from 'components/strategies/common/utils';
import { useContract } from 'hooks/useContract';
import { useTokens } from 'hooks/useTokens';
import { Strategy, useGetStrategList } from 'libs/queries';
import { Trending, useTrending } from 'libs/queries/extApi/tradeCount';
import { StrategyType } from 'libs/routing';
import { Token } from 'libs/tokens';
import { fetchTokenData } from 'libs/tokens/tokenHelperFn';
import { useEffect, useState } from 'react';
import { prettifyNumber } from 'utils/helpers';

interface TrendingPair {
pairAddress: string;
base: Token;
quote: Token;
trades: number;
}

const trendByPair = (trending?: Trending, tokenList: Token[] = []) => {
if (!trending || !tokenList.length) return [];
const tokens: Record<string, Token> = {};
for (const token of tokenList) {
tokens[token.address] = token;
}
const useTrendingPairs = (trending?: Trending) => {
const [loading, setLoading] = useState(true);
const { tokensMap, importToken } = useTokens();
const { Token } = useContract();

useEffect(() => {
const missingTokens = new Set<string>();
for (const { token0, token1 } of trending?.tradeCount ?? []) {
if (!tokensMap.has(token0.toLowerCase())) missingTokens.add(token0);
if (!tokensMap.has(token1.toLowerCase())) missingTokens.add(token1);
}
if (!missingTokens.size) return;
const getTokens = Array.from(missingTokens).map((address) => {
return fetchTokenData(Token, address);
});
Promise.all(getTokens).then((tokens) => {
tokens.forEach((data) => importToken(data));
setLoading(false);
});
}, [Token, importToken, tokensMap, trending?.tradeCount]);
if (!trending || loading) return [];

const pairs: Record<string, { trades: number; trades_24h: number }> = {};
for (const trade of trending.tradeCount) {
pairs[trade.pairAddresses] ||= { trades: 0, trades_24h: 0 };
pairs[trade.pairAddresses].trades += trade.strategyTrades;
pairs[trade.pairAddresses].trades_24h += trade.strategyTrades_24h;
}
console.log(pairs);
const list = Object.entries(pairs)
.filter(([, { trades_24h }]) => !!trades_24h)
.map(([pair, { trades }]) => ({
base: tokens[pair.split('/').shift()!],
quote: tokens[pair.split('/').pop()!],
.map(([pairAddress, { trades }]) => ({
pairAddress: pairAddress,
base: tokensMap.get(pairAddress.split('/').shift()!)!,
quote: tokensMap.get(pairAddress.split('/').pop()!)!,
trades,
}))
.sort((a, b) => b.trades - a.trades)
.splice(0, 10);

const result: TrendingPair[] = [];
for (let i = 0; i < 3; i++) {
const index = Math.floor(Math.random() * list.length);
Expand All @@ -40,17 +64,44 @@ const trendByPair = (trending?: Trending, tokenList: Token[] = []) => {
return result.sort((a, b) => b.trades - a.trades);
};

interface StrategyWithTradeCount extends Strategy {
trades: number;
type: StrategyType;
}
const useTrendStrategies = (trending?: Trending): StrategyWithTradeCount[] => {
const list = (trending?.tradeCount ?? [])
.filter((t) => !!t.strategyTrades_24h)
.sort((a, b) => b.strategyTrades - a.strategyTrades)
.splice(0, 10);
const record: Record<string, number> = {};
for (let i = 0; i < 3; i++) {
if (!list.length) break;
const index = Math.floor(Math.random() * list.length);
const item = list.splice(index, 1)[0];
record[item.id] = item.strategyTrades;
}
const query = useGetStrategList(Object.keys(record));
return (query.data ?? []).map((strategy) => ({
...strategy,
type: getStrategyType(strategy),
trades: record[strategy.id],
}));
};

export const ExplorerHeader = () => {
const { data: tokens } = useTokensQuery();
const { data: trending } = useTrending();
const pairs = trendByPair(trending, tokens);
const strategies = useTrendStrategies(trending);
const pairs = useTrendingPairs(trending);
console.log({ strategies, pairs });
return (
<header className="flex gap-16">
<header className="flex gap-32">
<article>
<h2>Total Trades</h2>
<p>{trending?.totalTradeCount}</p>
<p className="text-36 font-weight-700 font-title">
{trending?.totalTradeCount}
</p>
</article>
<article>
<article className="border-background-800 rounded border-2 p-20">
<h2>Populare Pairs</h2>
<table>
<thead>
Expand All @@ -60,30 +111,39 @@ export const ExplorerHeader = () => {
</tr>
</thead>
<tbody>
{pairs.map(({ base, quote, trades }) => (
<tr key={`${base.address}/${quote.address}`}>
{pairs.map(({ pairAddress, base, quote, trades }) => (
<tr key={pairAddress}>
<td>
<TokensOverlap tokens={[base, quote]} size={18} />
{base.symbol}/{quote.symbol}
{base?.symbol}/{quote?.symbol}
</td>
<td>{prettifyNumber(trades)}</td>
</tr>
))}
</tbody>
</table>
</article>
<article>
<article className="border-background-800 rounded border-2 p-20">
<h2>Trending Strategies</h2>
<table>
<thead>
<tr>
<td></td>
<td></td>
<td></td>
<td>ID</td>
<td>Types</td>
<td>Trades</td>
</tr>
</thead>
<tbody>
<tr></tr>
{strategies.map(({ id, idDisplay, base, quote, type, trades }) => (
<tr key={id}>
<td>
<TokensOverlap tokens={[base, quote]} size={18} />
{idDisplay}
</td>
<td>{type}</td>
<td>{prettifyNumber(trades)}</td>
</tr>
))}
</tbody>
</table>
</article>
Expand Down
3 changes: 2 additions & 1 deletion src/components/strategies/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Token } from 'libs/tokens';
import { formatNumber } from 'utils/helpers';
import { BaseOrder } from './types';
import { endOfDay, getUnixTime, startOfDay, subDays } from 'date-fns';
import { StrategyType } from 'libs/routing';

type StrategyOrderInput =
| { min: string; max: string }
Expand Down Expand Up @@ -35,7 +36,7 @@ export const isDisposableStrategy = (strategy: Strategy) => {
return false;
};

export const getStrategyType = (strategy: Strategy) => {
export const getStrategyType = (strategy: Strategy): StrategyType => {
if (isOverlappingStrategy(strategy)) return 'overlapping';
if (isDisposableStrategy(strategy)) return 'disposable';
return 'recurring';
Expand Down
23 changes: 23 additions & 0 deletions src/libs/queries/sdk/strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,29 @@ export const useGetUserStrategies = ({ user }: Props) => {
});
};

export const useGetStrategList = (ids: string[]) => {
const { isInitialized } = useCarbonInit();
const { tokens, getTokenById, importToken } = useTokens();
const { Token } = useContract();

return useQuery<Strategy[]>({
queryKey: QueryKey.strategy(ids.join()),
queryFn: async () => {
const getStrategies = ids.map((id) => carbonSDK.getStrategy(id));
const strategies = await Promise.all(getStrategies);
return buildStrategiesHelper({
strategies,
getTokenById,
importToken,
Token,
});
},
enabled: tokens.length > 0 && isInitialized,
staleTime: ONE_DAY_IN_MS,
retry: false,
});
};

export const useGetStrategy = (id: string) => {
const { isInitialized } = useCarbonInit();
const { tokens, getTokenById, importToken } = useTokens();
Expand Down
2 changes: 1 addition & 1 deletion src/pages/explorer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import {
} from 'components/explorer';
import { StrategyProvider, useStrategyCtx } from 'hooks/useStrategies';
import { ExplorerTabs } from 'components/explorer/ExplorerTabs';
import { ExplorerHeader } from 'components/explorer/ExplorerHeader';
import { useEffect, useState } from 'react';
import { explorerEvents } from 'services/events/explorerEvents';
import { lsService } from 'services/localeStorage';
import { ExplorerHeader } from 'components/explorer/ExplorerHeader';

const url = '/explore/$type';
export const ExplorerPage = () => {
Expand Down

0 comments on commit debdf37

Please sign in to comment.