diff --git a/packages/thirdweb/src/chain/index.ts b/packages/thirdweb/src/chain/index.ts index 3ffffd21434..ebb61cb38b2 100644 --- a/packages/thirdweb/src/chain/index.ts +++ b/packages/thirdweb/src/chain/index.ts @@ -122,10 +122,38 @@ export async function getChainDecimals(chain: Chain): Promise { return 18; }); } - // if we have a symbol, return it + // if we have decimals, return it return chain.nativeCurrency.decimals; } +/** + * Retrieves the name of the native currency for a given chain. + * If the chain object does not have a native currency name, it attempts to fetch the chain data and retrieve the native currency name from there. + * If fetching the chain data fails, it falls back to returning "ETH". + * @param chain The chain object for which to retrieve the native currency name. + * @returns A promise that resolves to the native currency name. + * @internal + */ +export async function getChainNativeCurrencyName( + chain: Chain, +): Promise { + if ( + typeof chain === "bigint" || + typeof chain === "number" || + !chain.nativeCurrency?.name + ) { + const chainId = getChainIdFromChain(chain); + return getChainDataForChainId(chainId) + .then((data) => data.nativeCurrency.name) + .catch(() => { + // if we fail to fetch the chain data, return 18 as a fallback (most likely it's 18) + return "ETH"; + }); + } + // if we have a name, return it + return chain.nativeCurrency.name; +} + type FetchChainResponse = | { data: ApiChain; diff --git a/packages/thirdweb/src/wallets/utils/getTokenBalance.ts b/packages/thirdweb/src/wallets/utils/getTokenBalance.ts index 6b4db1811fd..4fc6809591c 100644 --- a/packages/thirdweb/src/wallets/utils/getTokenBalance.ts +++ b/packages/thirdweb/src/wallets/utils/getTokenBalance.ts @@ -2,6 +2,7 @@ import { getChainSymbol, type Chain, getChainDecimals, + getChainNativeCurrencyName, } from "../../chain/index.js"; import type { ThirdwebClient } from "../../client/client.js"; import { getContract } from "../../contract/index.js"; @@ -24,6 +25,7 @@ type GetTokenBalanceResult = { decimals: number; displayValue: string; symbol: string; + name: string; }; /** @@ -54,16 +56,19 @@ export async function getTokenBalance( // native token case const rpcRequest = getRpcClient({ client, chain }); - const [nativeSymbol, nativeDecimals, nativeBalance] = await Promise.all([ - getChainSymbol(chain), - getChainDecimals(chain), - eth_getBalance(rpcRequest, { address: account.address }), - ]); + const [nativeSymbol, nativeDecimals, nativeName, nativeBalance] = + await Promise.all([ + getChainSymbol(chain), + getChainDecimals(chain), + getChainNativeCurrencyName(chain), + eth_getBalance(rpcRequest, { address: account.address }), + ]); return { value: nativeBalance, decimals: nativeDecimals, displayValue: formatUnits(nativeBalance, nativeDecimals), symbol: nativeSymbol, + name: nativeName, }; }