Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor example/asset list #175

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions examples/asset-list/components/asset-list/AssetListSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import React from 'react';
import { Text, Box } from '@interchain-ui/react';
import AssetsOverview from './AssetsOverview';
import { useChain } from '@cosmos-kit/react';
import { useAssets } from '../../hooks';
import { ChainName } from 'cosmos-kit';
import { useAssets, usePrices } from '@/hooks';


interface AssetListSectionProps {
chainName: ChainName;
Expand All @@ -12,7 +13,9 @@ interface AssetListSectionProps {

export const AssetListSection = ({ chainName }: AssetListSectionProps) => {
const { isWalletConnected } = useChain(chainName);
const { data, isLoading, refetch } = useAssets(chainName);
const { data: assets = [], isLoading, refetch } = useAssets(chainName);

const { data: prices = {} } = usePrices(chainName);

if (!isWalletConnected) {
return (
Expand Down Expand Up @@ -45,9 +48,9 @@ export const AssetListSection = ({ chainName }: AssetListSectionProps) => {
return (
<Box maxWidth="$containerMd" marginX="auto" marginBottom="$17">
<AssetsOverview
isLoading={isLoading || !data}
assets={data?.assets ?? []}
prices={data?.prices ?? {}}
isLoading={isLoading || !assets}
assets={assets}
prices={prices}
selectedChainName={chainName}
refetch={refetch}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '@interchain-ui/react';
import { useChainWallet, useManager } from '@cosmos-kit/react';
import BigNumber from 'bignumber.js';
import { ibc } from 'osmo-query';
import { ibc } from 'interchain-query';
import { StdFee, coins } from '@cosmjs/amino';
import { ChainName } from 'cosmos-kit';
import { KeplrWalletName } from '@/config';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ChainName } from 'cosmos-kit';
import { coins, StdFee } from '@cosmjs/amino';
import { useDisclosure, useChainUtils, useBalance, useTx } from '@/hooks';
import { KeplrWalletName } from '@/config';
import { ibc } from 'osmo-query';
import { ibc } from 'interchain-query';

import { PriceHash, TransferInfo, Transfer } from './types';

Expand Down
14 changes: 1 addition & 13 deletions examples/asset-list/components/asset-list/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,7 @@ export type PrettyAsset = {
denom: string;
};

export type Token = {
price: number;
denom: string;
symbol: string;
liquidity: number;
volume_24h: number;
volume_24h_change: number;
name: string;
price_24h_change: number;
price_7d_change: number;
exponent: number;
display: string;
};


export type PriceHash = {
[key: string]: number;
Expand Down
10 changes: 3 additions & 7 deletions examples/asset-list/config/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,29 @@ import {
cosmwasmProtoRegistry,
ibcProtoRegistry,
ibcAminoConverters,
osmosisAminoConverters,
osmosisProtoRegistry,
} from 'osmo-query';
} from 'interchain-query';

export const defaultChainName = 'osmosis';
export const defaultChainName = 'cosmoshub';
export const KeplrWalletName = 'keplr-extension';

export const chainassets: AssetList = assets.find(
(chain) => chain.chain_name === defaultChainName
) as AssetList;

export const coin: Asset = chainassets.assets.find(
(asset) => asset.base === 'uosmo'
(asset) => asset.base === 'uatom'
) as Asset;

const protoRegistry: ReadonlyArray<[string, GeneratedType]> = [
...cosmosProtoRegistry,
...cosmwasmProtoRegistry,
...ibcProtoRegistry,
...osmosisProtoRegistry,
];

const aminoConverters = {
...cosmosAminoConverters,
...cosmwasmAminoConverters,
...ibcAminoConverters,
...osmosisAminoConverters,
};

export const registry = new Registry(protoRegistry);
Expand Down
25 changes: 25 additions & 0 deletions examples/asset-list/hooks/newFunctionPlacedToChainRegistry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { CoinGeckoUSD } from '@/utils/types';
import { AssetList } from '@chain-registry/types';
import { DenomPriceMap } from '@chain-registry/utils';

// put some may have issue function. will put to chain registry later, we will see.

// replace mapCoinGeckoPricesToDenoms in chain-registry, use gecko_id to map denom, will have duplicate asset , cause original mapCoinGeckoPricesToDenoms function can not use
export const mapCoinGeckoPricesToDenomsM = (assetLists: AssetList[], prices: Record<string, CoinGeckoUSD>): DenomPriceMap => {
const symbolCoinGeckoIdMap = assetLists.flatMap(a => a.assets).reduce((map: any, asset) => {
if (asset.coingecko_id) {
map[asset.symbol] = prices[asset.coingecko_id]
}
return map
}, {})

const final = assetLists.flatMap(a => a.assets).reduce((map: any, asset) => {
if (asset.symbol && symbolCoinGeckoIdMap[asset.symbol]) {
map[asset.base] = symbolCoinGeckoIdMap[asset.symbol].usd
}
return map
}, {})

return final
}

150 changes: 46 additions & 104 deletions examples/asset-list/hooks/queries/useAssets.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
import { PrettyAsset } from '@/components';
import { Coin } from '@cosmjs/stargate';
import { useChain } from '@cosmos-kit/react';
import { UseQueryResult } from '@tanstack/react-query';
import BigNumber from 'bignumber.js';
import { useEffect, useMemo } from 'react';
import { useChainUtils } from '../useChainUtils';
import { useQueryHooks } from './useQueryHooks';
import { usePrices } from './usePrices';
import { useTopTokens } from './useTopTokens';
import { getPagination } from './useTotalAssets';
import { useChain } from "@cosmos-kit/react"
import { useQueryHooks } from "./useQueryHooks";
import { UseQueryResult } from "@tanstack/react-query";
import { getPagination } from "./useTotalAssets";
import { useMemo } from "react";
import { Coin } from "interchain-query/cosmos/base/v1beta1/coin";
import {
getChainNameByStakingDenom,
convertBaseUnitToDisplayUnitByDenom,
convertBaseUnitToDollarValueByDenom
} from '@chain-registry/utils'
import { useGeckoPrices } from './useGeckoPrices';
import BigNumber from "bignumber.js";

import { assets, chains } from '@/utils/local-chain-registry'

(BigInt.prototype as any).toJSON = function () {
return this.toString();
};

const MAX_TOKENS_TO_SHOW = 50;

export const useAssets = (chainName: string) => {
const { address } = useChain(chainName);

const { cosmosQuery, isReady, isFetching } = useQueryHooks(chainName);
// address for balance
const { address } = useChain(chainName)

const allBalancesQuery: UseQueryResult<Coin[]> =
// init cosmos query client for balance
const { cosmosQuery, isReady } = useQueryHooks(chainName);
const { data: allBalances = [], isLoading: isAllBalanceLoading, refetch: refetchAllBalances }: UseQueryResult<Coin[]> =
cosmosQuery.bank.v1beta1.useAllBalances({
request: {
address: address || '',
Expand All @@ -33,99 +37,37 @@ export const useAssets = (chainName: string) => {
},
});

const pricesQuery = usePrices(chainName);
const topTokensQuery = useTopTokens();
// get gecko prices, get price map
const { data: priceMap = {}, isLoading: isGeckoPricesLading } = useGeckoPrices()

const dataQueries = {
allBalances: allBalancesQuery,
topTokens: topTokensQuery,
prices: pricesQuery,
};
const data = useMemo(() => {

const queriesToReset = [dataQueries.allBalances];
const queriesToRefetch = [dataQueries.allBalances];
const assetToDisplay = assets.find(a => a.chain_name === chainName)?.assets || []

useEffect(() => {
queriesToReset.forEach((query) => query.remove());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chainName]);
return assetToDisplay.map((asset) => {

const queries = Object.values(dataQueries);
const isInitialFetching = queries.some(({ isLoading }) => isLoading);
const isRefetching = queries.some(({ isRefetching }) => isRefetching);
const isLoading = isFetching || isInitialFetching || isRefetching;
const { base, symbol } = asset

type AllQueries = typeof dataQueries;
const amount = allBalances.find((balance: Coin) => balance.denom === base)?.amount || '0'
const dollarValue = convertBaseUnitToDollarValueByDenom(assets, priceMap, base, amount, chainName)
const displayAmount = convertBaseUnitToDisplayUnitByDenom(assets, base, amount, chainName)

type QueriesData = {
[Key in keyof AllQueries]: NonNullable<AllQueries[Key]['data']>;
};
const prettyChainName = getChainNameByStakingDenom(chains, base) || ''

const {
ibcAssets,
getAssetByDenom,
convRawToDispAmount,
calcCoinDollarValue,
denomToSymbol,
getPrettyChainName,
} = useChainUtils(chainName);
return {
symbol,
logoUrl: asset?.logo_URIs?.png || asset?.logo_URIs?.svg,
prettyChainName,
displayAmount,
dollarValue,
amount,
denom: base,
};
}).sort((a, b) => BigNumber(a.displayAmount).lte(b.displayAmount) ? 1 : -1)

const data = useMemo(() => {
if (isLoading) return;

const queriesData = Object.fromEntries(
Object.entries(dataQueries).map(([key, query]) => [key, query.data])
) as QueriesData;

const { allBalances, prices, topTokens } = queriesData;

const nativeAndIbcBalances: Coin[] = allBalances.filter(
({ denom }) => !denom.startsWith('gamm') && prices[denom]
);

const emptyBalances: Coin[] = ibcAssets
.filter(({ base }) => {
const notInBalances = !nativeAndIbcBalances.find(
({ denom }) => denom === base
);
return notInBalances && prices[base];
})
.filter((asset) => {
const isWithinLimit = ibcAssets.length <= MAX_TOKENS_TO_SHOW;
return isWithinLimit || topTokens.includes(asset.symbol);
})
.map((asset) => ({ denom: asset.base, amount: '0' }));

const finalAssets = [...nativeAndIbcBalances, ...emptyBalances]
.map(({ amount, denom }) => {
const asset = getAssetByDenom(denom);
const symbol = denomToSymbol(denom);
const dollarValue = calcCoinDollarValue(prices, { amount, denom });
return {
symbol,
logoUrl: asset.logo_URIs?.png || asset.logo_URIs?.svg,
prettyChainName: getPrettyChainName(denom),
displayAmount: convRawToDispAmount(denom, amount),
dollarValue,
amount,
denom,
};
})
.sort((a, b) =>
new BigNumber(a.dollarValue).lt(b.dollarValue) ? 1 : -1
);

return {
prices,
allBalances,
assets: finalAssets as PrettyAsset[],
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoading]);

const refetch = () => {
queriesToRefetch.forEach((query) => query.refetch());
};

return { data, isLoading, refetch };
};
}, [chainName, allBalances, priceMap])

const isLoading = [isAllBalanceLoading, isGeckoPricesLading].some(isLoading => isLoading === true)

return { data, isLoading, refetch: refetchAllBalances }
}
39 changes: 39 additions & 0 deletions examples/asset-list/hooks/queries/useGeckoPrices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { DenomPriceMap, mapCoinGeckoPricesToDenoms } from '@chain-registry/utils';
import { useQuery } from '@tanstack/react-query';
import { handleError } from './useTopTokens';
import { CoinGeckoUSD } from '@/utils/types';
import { assets } from '@/utils/local-chain-registry'

const GECKO_PRICE_QUERY_KEY = 'gecko_prices'

const getGeckoIds = () => {
const geckoIds: string[] = []
assets.forEach(assetList => {
assetList.assets.forEach(asset => {
if (asset.coingecko_id) {
geckoIds.push(asset.coingecko_id)
}
})
})
return geckoIds
}

const fetchPrices = async (
geckoIds: string[]
): Promise<Record<string, CoinGeckoUSD>> => {
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${geckoIds.join()}&vs_currencies=usd`;

return fetch(url)
.then(handleError)
.then((res) => res.json());
};

export const useGeckoPrices = () => {
const geckoIds = getGeckoIds()
return useQuery({
queryKey: [GECKO_PRICE_QUERY_KEY],
queryFn: () => fetchPrices(geckoIds),
select: (geckoPrices): DenomPriceMap => mapCoinGeckoPricesToDenoms(assets, geckoPrices),
staleTime: Infinity,
});
};
47 changes: 47 additions & 0 deletions examples/asset-list/hooks/queries/useOsmosisToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useQuery } from '@tanstack/react-query';



// remove this hook do not fetch any token from api, just use chain registry
type Token = {
price: number;
denom: string;
symbol: string;
liquidity: number;
volume_24h: number;
volume_24h_change: number;
name: string;
price_24h_change: number;
price_7d_change: number;
exponent: number;
display: string;
};

export const handleError = (resp: Response) => {
if (!resp.ok) throw Error(resp.statusText);
return resp;
};

const fetchTokens = async (): Promise<Token[]> => {
const url = 'https://api-osmosis.imperator.co/tokens/v2/all';
return fetch(url)
.then(handleError)
.then((res) => res.json());
};

const MAX_TOP_TOKENS = 60;

const filterTopTokens = (tokens: Token[]) => {
return tokens
.sort((a, b) => b.liquidity - a.liquidity)
.slice(0, MAX_TOP_TOKENS)
};

export const useOsmosisToken = () => {
return useQuery({
queryKey: ['osmosis_tokens'],
queryFn: fetchTokens,
select: filterTopTokens,
staleTime: Infinity,
});
};
Loading