Skip to content

Commit

Permalink
update package.json and fix some unit functions
Browse files Browse the repository at this point in the history
  • Loading branch information
cmaaawscodepipelinedeploy committed Apr 22, 2024
1 parent de16efe commit 93f7dad
Show file tree
Hide file tree
Showing 15 changed files with 477 additions and 713 deletions.
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
71 changes: 26 additions & 45 deletions examples/asset-list/hooks/queries/useAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@ import { useQueryHooks } from "./useQueryHooks";
import { UseQueryResult } from "@tanstack/react-query";
import { getPagination } from "./useTotalAssets";
import { useMemo } from "react";
import { useOsmosisToken } from "./useOsmosisToken";
import { Coin } from "osmo-query/dist/codegen/cosmos/base/v1beta1/coin";
import { Coin } from "interchain-query/cosmos/base/v1beta1/coin";
import {
getAssetByDenom,
getChainNameByDenom,
convertBaseUnitToDollarValue,
getAssetBySymbol,
convertBaseUnitToDisplayUnit
getChainNameByStakingDenom,
convertBaseUnitToDisplayUnitByDenom,
convertBaseUnitToDollarValueByDenom
} from '@chain-registry/utils'
import { useGeckoPrices } from './useGeckoPrices';
import { getAssetsByChainName } from '@/utils/local-chain-registry'
import BigNumber from "bignumber.js";

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

(BigInt.prototype as any).toJSON = function () {
return this.toString();
};
Expand All @@ -39,54 +37,37 @@ export const useAssets = (chainName: string) => {
},
});

// get osmosis token
const { data: topTokens = [], isLoading: isTopTokensLoading } = useOsmosisToken();

// get gecko prices, get price map
const { data: priceMap = null, isLoading: isGeckoPricesLading } = useGeckoPrices()
const { data: priceMap = {}, isLoading: isGeckoPricesLading } = useGeckoPrices()

const data = useMemo(() => {

if (priceMap) {

const assets = getAssetsByChainName(chainName)

return topTokens.map((token) => {

const { denom, symbol } = token
const assetToDisplay = assets.find(a => a.chain_name === chainName)?.assets || []

const asset = getAssetByDenom(assets, token.denom, chainName)
return assetToDisplay.map((asset) => {

const amount = allBalances.find((balance: Coin) => balance.denom === denom)?.amount || '0'
const { base, symbol } = asset

let dollarValue = '0'
const assetBySymbol = getAssetBySymbol(assets, symbol)
if (assetBySymbol) {
dollarValue = convertBaseUnitToDollarValue(assets, priceMap, symbol, amount)
}
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)

let displayAmount = '0'
if (assetBySymbol) {
displayAmount = convertBaseUnitToDisplayUnit(assets, symbol, amount)
}
const prettyChainName = getChainNameByStakingDenom(chains, base) || ''

const prettyChainName = getChainNameByDenom(assets, denom) || ''
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)

return {
symbol,
logoUrl: asset?.logo_URIs?.png || asset?.logo_URIs?.svg,
prettyChainName,
displayAmount,
dollarValue,
amount,
denom,
};
}).sort((a, b) => BigNumber(a.displayAmount).lte(b.displayAmount) ? 1 : -1)
}
return []
}, [topTokens, chainName, allBalances, priceMap])
}, [chainName, allBalances, priceMap])

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

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

const GECKO_PRICE_QUERY_KEY = 'gecko_prices'

const getGeckoIds = () => {
const geckoIds: string[] = []
mainnetAssets.forEach(assetList => {
assets.forEach(assetList => {
assetList.assets.forEach(asset => {
if (asset.coingecko_id) {
geckoIds.push(asset.coingecko_id)
Expand All @@ -33,9 +31,9 @@ const fetchPrices = async (
export const useGeckoPrices = () => {
const geckoIds = getGeckoIds()
return useQuery({
queryKey: [GECKO_PRICE_QUERY_KEY, geckoIds],
queryKey: [GECKO_PRICE_QUERY_KEY],
queryFn: () => fetchPrices(geckoIds),
select: (geckoPrices): DenomPriceMap => mapCoinGeckoPricesToDenomsM(assets, geckoPrices),
select: (geckoPrices): DenomPriceMap => mapCoinGeckoPricesToDenoms(assets, geckoPrices),
staleTime: Infinity,
});
};
3 changes: 3 additions & 0 deletions examples/asset-list/hooks/queries/useOsmosisToken.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
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;
Expand Down
6 changes: 3 additions & 3 deletions examples/asset-list/hooks/queries/useQueryHooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useChain } from '@cosmos-kit/react';
import { useRpcEndpoint, useRpcClient, createRpcQueryHooks } from 'osmo-query';
import { useRpcEndpoint, useRpcClient, createRpcQueryHooks } from 'interchain-query';

export const useQueryHooks = (chainName: string, extraKey?: string) => {
const { address, getRpcEndpoint } = useChain(chainName);
Expand Down Expand Up @@ -27,12 +27,12 @@ export const useQueryHooks = (chainName: string, extraKey?: string) => {
},
});

const { cosmos: cosmosQuery, osmosis: osmosisQuery } = createRpcQueryHooks({
const { cosmos: cosmosQuery } = createRpcQueryHooks({
rpc: rpcClientQuery.data,
});

const isReady = !!address && !!rpcClientQuery.data;
const isFetching = rpcEndpointQuery.isFetching || rpcClientQuery.isFetching;

return { cosmosQuery, osmosisQuery, isReady, isFetching };
return { cosmosQuery, isReady, isFetching };
};
87 changes: 7 additions & 80 deletions examples/asset-list/hooks/queries/useTotalAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ import BigNumber from 'bignumber.js';
import { useEffect, useMemo } from 'react';
import { useChainUtils } from '../useChainUtils';
import { usePrices } from './usePrices';
import { defaultChainName as osmoChainName } from '@/config';
import { Pool } from 'osmo-query/dist/codegen/osmosis/gamm/pool-models/balancer/balancerPool';
import { convertGammTokenToDollarValue } from '@/utils';
import { useQueryHooks } from './useQueryHooks';

(BigInt.prototype as any).toJSON = function () {
Expand All @@ -25,11 +22,9 @@ export const getPagination = (limit: bigint) => ({
export const useTotalAssets = (chainName: string) => {
const { address } = useChain(chainName);

const { cosmosQuery, osmosisQuery, isReady, isFetching } =
const { cosmosQuery, isReady, isFetching } =
useQueryHooks(chainName);

const isOsmosisChain = chainName === osmoChainName;

const allBalancesQuery: UseQueryResult<Coin[]> =
cosmosQuery.bank.v1beta1.useAllBalances({
request: {
Expand All @@ -42,7 +37,7 @@ export const useTotalAssets = (chainName: string) => {
},
});

const delegationsQuery: UseQueryResult<Coin[]> =
const delegationsQuery: UseQueryResult<(Coin | undefined)[]> =
cosmosQuery.staking.v1beta1.useDelegatorDelegations({
request: {
delegatorAddr: address || '',
Expand All @@ -55,39 +50,12 @@ export const useTotalAssets = (chainName: string) => {
},
});

const lockedCoinsQuery: UseQueryResult<Coin[]> =
osmosisQuery.lockup.useAccountLockedCoins({
request: {
owner: address || '',
},
options: {
enabled: isReady && isOsmosisChain,
select: ({ coins }) => coins || [],
staleTime: Infinity,
},
});

const poolsQuery: UseQueryResult<Pool[]> = osmosisQuery.gamm.v1beta1.usePools(
{
request: {
pagination: getPagination(5000n),
},
options: {
enabled: isReady && isOsmosisChain,
select: ({ pools }) => pools || [],
staleTime: Infinity,
},
}
);

const pricesQuery = usePrices(chainName);

const dataQueries = {
pools: poolsQuery,
prices: pricesQuery,
allBalances: allBalancesQuery,
delegations: delegationsQuery,
lockedCoins: lockedCoinsQuery,
};

const queriesToReset = [dataQueries.allBalances, dataQueries.delegations];
Expand Down Expand Up @@ -121,15 +89,15 @@ export const useTotalAssets = (chainName: string) => {
) as QueriesData;

const {
allBalances,
delegations,
lockedCoins = [],
pools = [],
allBalances = [],
delegations = [],
// lockedCoins = [],
// pools = [],
prices = {},
} = queriesData;

const stakedTotal = delegations
?.map((coin) => calcCoinDollarValue(prices, coin))
?.map((coin) => calcCoinDollarValue(prices, coin as Coin))
.reduce((total, cur) => total.plus(cur), zero)
.toString();

Expand All @@ -142,47 +110,6 @@ export const useTotalAssets = (chainName: string) => {
let bondedTotal;
let liquidityTotal;

if (isOsmosisChain) {
const liquidityCoins = (allBalances ?? []).filter(({ denom }) =>
denom.startsWith('gamm')
);
const gammTokenDenoms = [
...(liquidityCoins ?? []),
...(lockedCoins ?? []),
].map(({ denom }) => denom);

const uniqueDenoms = [...new Set(gammTokenDenoms)];

const poolsMap: Record<string, Pool> = pools
.filter(({ totalShares }) => uniqueDenoms.includes(totalShares.denom))
.filter((pool) => !pool?.$typeUrl?.includes('stableswap'))
.filter(({ poolAssets }) => {
return poolAssets.every(({ token }) => {
const isGammToken = token.denom.startsWith('gamm/pool');
return !isGammToken && prices[token.denom];
});
})
.reduce((prev, cur) => ({ ...prev, [cur.totalShares.denom]: cur }), {});

bondedTotal = lockedCoins
.map((coin) => {
const poolData = poolsMap[coin.denom];
if (!poolData) return '0';
return convertGammTokenToDollarValue(coin, poolData, prices);
})
.reduce((total, cur) => total.plus(cur), zero)
.toString();

liquidityTotal = liquidityCoins
.map((coin) => {
const poolData = poolsMap[coin.denom];
if (!poolData) return '0';
return convertGammTokenToDollarValue(coin, poolData, prices);
})
.reduce((total, cur) => total.plus(cur), zero)
.toString();
}

const total = [stakedTotal, balancesTotal, bondedTotal, liquidityTotal]
.reduce((total, cur) => total.plus(cur || 0), zero)
.decimalPlaces(2)
Expand Down
4 changes: 2 additions & 2 deletions examples/asset-list/hooks/useTx.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { cosmos } from 'osmo-query';
import { cosmos } from 'interchain-query';
import { isDeliverTxSuccess, StdFee } from '@cosmjs/stargate';
import { toast, ToastShape } from '@interchain-ui/react';
import { useChain } from '@cosmos-kit/react';
import { TxRaw } from 'osmo-query/dist/codegen/cosmos/tx/v1beta1/tx';
import { TxRaw } from 'interchain-query/cosmos/tx/v1beta1/tx';

interface Msg {
typeUrl: string;
Expand Down
Loading

0 comments on commit 93f7dad

Please sign in to comment.