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

fix: user added chains price id #1571

Merged
merged 1 commit into from
Oct 1, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,13 @@ import { useParams } from 'react-router';
import { BN } from '@polkadot/util';

import { AccountContext, ActionContext, Warning } from '../../components';
import { useAccountAssets, useBalances, useCurrency, useFullscreen, useInfo, usePrices, useTranslation } from '../../hooks';
import { useAccountAssets, useBalances, useCurrency, useFullscreen, useInfo, usePrices, useTokenPrice, useTranslation } from '../../hooks';
import { getValue } from '../../popup/account/util';
import HistoryModal from '../../popup/history/modal/HistoryModal';
import { AccountLabel } from '../../popup/home/AccountLabel';
import ReceiveModal from '../../popup/receive/ReceiveModal';
import { ASSET_HUBS, GOVERNANCE_CHAINS, STAKING_CHAINS } from '../../util/constants';
import getParentNameSuri from '../../util/getParentNameSuri';
import { getPriceIdByChainName } from '../../util/utils';
import FullScreenHeader from '../governance/FullScreenHeader';
import Bread from '../partials/Bread';
import DeriveAccountModal from '../partials/DeriveAccountModal';
Expand Down Expand Up @@ -70,6 +69,7 @@ export default function AccountDetails (): React.ReactElement {
const [unlockInformation, setUnlockInformation] = useState<UnlockInformationType | undefined>();

const assetId = useMemo(() => assetIdOnAssetHub !== undefined ? assetIdOnAssetHub : selectedAsset?.assetId, [assetIdOnAssetHub, selectedAsset?.assetId]);
const { price: currentPrice } = useTokenPrice(address, assetId);

const balances = useBalances(address, refreshNeeded, setRefreshNeeded, undefined, assetId || undefined);

Expand Down Expand Up @@ -106,21 +106,6 @@ export default function AccountDetails (): React.ReactElement {
balancesToShow?.soloTotal && balancesToShow?.pooledBalance && !balancesToShow.soloTotal.isZero() && !balancesToShow.pooledBalance.isZero()
, [balancesToShow?.pooledBalance, balancesToShow?.soloTotal]);

const currentPrice = useMemo((): number | undefined => {
const selectedAssetPriceId = selectedAsset?.priceId;

if (selectedAsset && !selectedAssetPriceId) {
// price is 0 for assets with no priceId
return 0;
}

const _priceId = getPriceIdByChainName(chainName);
const currentAssetPrices = pricesInCurrency?.prices?.[(selectedAssetPriceId || _priceId)];
const mayBeTestNetPrice = pricesInCurrency?.prices && !currentAssetPrices ? 0 : undefined;

return currentAssetPrices?.value || mayBeTestNetPrice;
}, [selectedAsset, chainName, pricesInCurrency?.prices]);

useEffect(() => {
// reset assetId on chain switch
assetIdOnAssetHub && setAssetIdOnAssetHub(undefined);
Expand Down
2 changes: 1 addition & 1 deletion packages/extension-polkagate/src/hooks/useBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export default function useBalances (address: string | undefined, refresh?: bool
return;
}

const ED = api.consts['balances']['existentialDeposit'] as unknown as BN;
const ED = api.consts['balances'] ? api.consts['balances']['existentialDeposit'] as unknown as BN : BN_ZERO;

formatted && api.derive.balances?.all(formatted).then((allBalances) => {
//@ts-ignore
Expand Down
15 changes: 8 additions & 7 deletions packages/extension-polkagate/src/hooks/useTokenPrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import type { Price } from '../util/types';
import { createAssets } from '@polkagate/apps-config/assets';
import { useMemo } from 'react';

import { useUserAddedPriceId } from '../fullscreen/addNewChain/utils';
import { toCamelCase } from '../fullscreen/governance/utils/util';
import { ASSET_HUBS, NATIVE_TOKEN_ASSET_ID } from '../util/constants';
import { getPriceIdByChainName } from '../util/utils';
import { useChain, useChainName, usePrices } from '.';
import { useInfo, usePrices } from '.';

const DEFAULT_PRICE = {
price: undefined,
Expand All @@ -25,13 +26,13 @@ const assetsChains = createAssets();
* @returns price : price of the token which the address is already switched to
*/
export default function useTokenPrice (address: string | undefined, assetId?: number): Price | typeof DEFAULT_PRICE {
const chainName = useChainName(address);
const chain = useChain(address);
const isAssetHub = ASSET_HUBS.includes(chain?.genesisHash || '');

const { chainName, genesisHash } = useInfo(address);
const userAddedPriceId = useUserAddedPriceId(genesisHash);
Nick-1979 marked this conversation as resolved.
Show resolved Hide resolved
const pricesInCurrencies = usePrices();
const mayBeAssetsOnMultiAssetChains = assetsChains[toCamelCase(chainName || '')];

const isAssetHub = ASSET_HUBS.includes(genesisHash || '');
Nick-1979 marked this conversation as resolved.
Show resolved Hide resolved

const _assetId = assetId !== undefined
? assetId
: isAssetHub
Expand All @@ -46,7 +47,7 @@ export default function useTokenPrice (address: string | undefined, assetId?: nu
// FixMe, on second fetch of asset id its type will get string which is weird!!
const priceId = _assetId !== undefined && _assetId > NATIVE_TOKEN_ASSET_ID
? mayBeAssetsOnMultiAssetChains?.find(({ id }) => id === Number(_assetId))?.priceId
: getPriceIdByChainName(chainName);
: userAddedPriceId || getPriceIdByChainName(chainName);

const mayBePriceValue = priceId ? pricesInCurrencies.prices?.[priceId]?.value || 0 : 0;

Expand All @@ -55,5 +56,5 @@ export default function useTokenPrice (address: string | undefined, assetId?: nu
priceChainName: chainName?.toLocaleLowerCase(),
priceDate: pricesInCurrencies.date
};
}, [_assetId, chainName, mayBeAssetsOnMultiAssetChains, pricesInCurrencies]);
}, [_assetId, chainName, mayBeAssetsOnMultiAssetChains, pricesInCurrencies, userAddedPriceId]);
}
12 changes: 10 additions & 2 deletions packages/extension-polkagate/src/util/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { Chain } from '@polkadot/extension-chains/types';
import type { Text } from '@polkadot/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Compact, u128 } from '@polkadot/types-codec';
import type { DropdownOption, FastestConnectionType, RecentChainsType, TransactionDetail } from './types';
import type { DropdownOption, FastestConnectionType, RecentChainsType, TransactionDetail, UserAddedChains } from './types';

import { ApiPromise, WsProvider } from '@polkadot/api';
import { BN, BN_TEN, BN_ZERO, hexToBn, hexToU8a, isHex } from '@polkadot/util';
Expand Down Expand Up @@ -371,11 +371,19 @@ export const getProfileColor = (index: number, theme: Theme): string => {
return PROFILE_COLORS[0][theme.palette.mode];
};

export const getPriceIdByChainName = (chainName?: string) => {
export const getPriceIdByChainName = (chainName?: string, useAddedChains?: UserAddedChains) => {
Nick-1979 marked this conversation as resolved.
Show resolved Hide resolved
if (!chainName) {
return '';
}

if (useAddedChains) {
const maybeUserAddedPriceId = Object.entries(useAddedChains).find(([_, { chain }]) => chain?.replace(/\s/g, '')?.toLowerCase() === chainName.toLowerCase())?.[1]?.priceId;

if (maybeUserAddedPriceId) {
return maybeUserAddedPriceId;
}
}

const _chainName = (sanitizeChainName(chainName) as unknown as string).toLocaleLowerCase();

return EXTRA_PRICE_IDS[_chainName] ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async function getAssetOnRelayChain (addresses, chainName, userAddedEndpoints) {
const genesisHash = api.genesisHash.toString();
const priceId = TEST_NETS.includes(genesisHash)
? undefined
: getPriceIdByChainName(chainName);
: getPriceIdByChainName(chainName, userAddedEndpoints);

results[address] = [{ // since some chains may have more than one asset hence we use an array here! even thought its not needed for relay chains but just to be as a general rule.
assetId: NATIVE_TOKEN_ASSET_ID, // Rule: we set asset id 0 for native tokens
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

import { createWsEndpoints } from '@polkagate/apps-config';

import { sanitizeChainName } from '../../utils';

/**
* to get all available chain endpoints of a chain except light client
* @param {string} chainName
Expand All @@ -18,7 +16,7 @@ export function getChainEndpoints (chainName, userAddedEndpoints) {
.filter((endpoint) => endpoint.info && endpoint.info.toLowerCase() === chainName.toLowerCase() && !endpoint.isDisabled && !endpoint?.isLightClient);

if (!endpoints.length && userAddedEndpoints) {
const maybeEndpoint = Object.entries(userAddedEndpoints).find(([_, { chain }]) => sanitizeChainName(chain)?.toLowerCase() === chainName.toLowerCase());
const maybeEndpoint = Object.entries(userAddedEndpoints).find(([_, { chain }]) => chain?.replace(/\s/g, '')?.toLowerCase() === chainName.toLowerCase());

// @ts-ignore
endpoints = maybeEndpoint ? [{ text: 'endpoint', value: maybeEndpoint[1].endpoint }] : [];
Expand Down
Loading